/**
 * 圆方之间π - Between Circle & Square π
 * 主脚本文件
 */

// 常量定义
const PI = Math.PI;
const REAL_PI_VALUE = 3.14159265358979323846;

// DOM 元素 - 核心组件
const simulationCanvas = document.getElementById('simulationCanvas');
const convergenceCanvas = document.getElementById('convergenceCanvas');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
const speedRange = document.getElementById('speedRange');
const speedValue = document.getElementById('speedValue');
const themeToggle = document.getElementById('themeToggle');

// DOM 元素 - 数据显示
const totalPointsElement = document.getElementById('totalPoints');
const circlePointsElement = document.getElementById('circlePoints');
const percentageElement = document.getElementById('percentage');
const piValueElement = document.getElementById('piValue');
const piValueOverlayElement = document.getElementById('piValueOverlay');
const errorElement = document.getElementById('error');
const pointsRadios = document.querySelectorAll('input[name="pointsPerIteration"]');

// DOM 元素 - 新界面组件
const navTabs = document.querySelectorAll('.nav-tab');
const sidebarSections = document.querySelectorAll('.sidebar-section');
const clearChartBtn = document.getElementById('clearChartBtn');
const gridToggle = document.getElementById('gridToggle');
const axesToggle = document.getElementById('axesToggle');
const pointSizeRange = document.getElementById('pointSizeRange');
const accuracyBar = document.getElementById('accuracyBar');
const accuracyValue = document.getElementById('accuracyValue');
const convergenceSpeedElement = document.getElementById('convergenceSpeed');
const bestEstimateElement = document.getElementById('bestEstimate');

// DOM 元素 - 页面导航
const navItems = document.querySelectorAll('.nav-item');
const pageContainers = document.querySelectorAll('.page-container');
const navigateButtons = document.querySelectorAll('[data-navigate]');
const heroButtons = document.querySelectorAll('[data-navigate]');

// 全局变量
let simulationCtx, convergenceCtx;
let animationId = null;
let isRunning = false;
let canvasSize = 0;
let centerX = 0, centerY = 0, radius = 0;
let totalPoints = 0;
let circlePoints = 0;
let speed = 10;
let pointsPerIteration = 1;
let convergenceData = [];
let isDarkTheme = false;
let pointRadius = 3; // 默认点大小
let showGrid = true;
let showAxes = true;
let particles = []; // 粒子数组
let points = []; // 模拟点数组
let bestPiEstimate = 0; // 最佳π估计值
let convergenceSpeed = 0; // 收敛速度
let devicePixelRatio = window.devicePixelRatio || 1; // 获取设备像素比

// 页面导航相关变量
let currentPage = 'welcome'; // 当前页面
let isNavigating = false; // 是否正在导航中
let simulationHistory = []; // 模拟历史记录
let analysisChart = null; // 分析图表实例

// 🚀 国奖级功能变量
let achievementSystem = {
    milestones: [90, 95, 98, 99, 99.9],
    achieved: [],
    lastAccuracy: 0
};
let particleContainer = null;
let isParticleEffectActive = false;

// AI智能助手系统
let aiAssistant = {
    lastAnalysis: 0,
    suggestions: [
        "尝试增加每次迭代点数至100，可提升收敛速度",
        "当前精度已稳定，建议重置后进行新一轮模拟",
        "速度设置过低，建议调至30-50获得最佳体验",
        "精度提升缓慢，建议增加迭代点数到1000",
        "模拟已接近收敛，可尝试挑战更高精度"
    ],
    isAnalyzing: false
};

// 模拟会话跟踪
let simulationStartTime = 0;

// 图表样式配置
const chartConfig = {
    maxDataPoints: 100,
    lineColor: '#4f46e5',
    lineWidth: 2,
    gridColor: '#e5e7eb',
    textColor: '#4b5563',
    piLineColor: 'rgba(236, 72, 153, 0.6)',
    showAnimation: true,
    animationDuration: 800
};

// 初始化
function init() {
    try {
        // 检查本地存储中的主题设置
        checkThemePreference();

        // 初始化页面导航
        setupPageNavigation();

        // 初始化粒子背景
        initParticlesBackground();

        // 添加鼠标跟踪效果
        addMouseTrackingEffects();

        // 优化动画性能
        optimizeAnimations();

        // 添加动画类
        addAnimationClasses();

        // 只在模拟页面初始化Canvas相关功能
        if (currentPage === 'simulation' || simulationCanvas) {
            // 设置Canvas上下文
            setupCanvas();

            // 初始化画布
            resizeCanvas();
            drawEmptyCanvas();

            // 初始化图表
            drawEmptyChart();

            // 初始化粒子
            initParticles();
        }

        // 添加事件监听
        setupEventListeners();

        // 初始化标签页
        setupTabs();

        // 初始化新控件
        setupAdditionalControls();

    } catch (error) {
        console.error('Initialization error:', error);
        showErrorMessage('初始化失败，请刷新页面重试');
    }
}

// 设置Canvas上下文
function setupCanvas() {
    if (simulationCanvas && convergenceCanvas) {
        simulationCtx = simulationCanvas.getContext('2d');
        convergenceCtx = convergenceCanvas.getContext('2d');

        // 启用抗锯齿
        simulationCtx.imageSmoothingEnabled = true;
        simulationCtx.imageSmoothingQuality = 'high';
        convergenceCtx.imageSmoothingEnabled = true;
        convergenceCtx.imageSmoothingQuality = 'high';
    }
}

// 设置标签页
function setupTabs() {
    navTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            // 移除所有标签和内容的活动状态
            navTabs.forEach(t => t.classList.remove('active'));
            sidebarSections.forEach(s => s.classList.remove('active'));
            
            // 添加活动状态到当前标签和对应内容
            tab.classList.add('active');
            const targetId = `${tab.dataset.target}-section`;
            document.getElementById(targetId).classList.add('active');
        });
    });
}

// 设置附加控件
function setupAdditionalControls() {
    // 清除图表按钮
    if (clearChartBtn) {
        clearChartBtn.addEventListener('click', clearChart);
    }
    
    // 网格切换
    if (gridToggle) {
        gridToggle.addEventListener('change', () => {
            showGrid = gridToggle.checked;
            drawEmptyCanvas();
        });
    }
    
    // 坐标轴切换
    if (axesToggle) {
        axesToggle.addEventListener('change', () => {
            showAxes = axesToggle.checked;
            drawEmptyCanvas();
        });
    }
    
    // 点大小控制
    if (pointSizeRange) {
        const pointSizeValueElement = document.getElementById('pointSizeValue');

        // 初始化显示点大小值
        if (pointSizeValueElement) {
            pointSizeValueElement.textContent = pointSizeRange.value;
        }

        pointSizeRange.addEventListener('input', () => {
            pointRadius = parseFloat(pointSizeRange.value);
            // 更新显示的点大小值
            if (pointSizeValueElement) {
                pointSizeValueElement.textContent = pointRadius;

                // 添加动画效果
                pointSizeValueElement.classList.add('changing');
                setTimeout(() => {
                    pointSizeValueElement.classList.remove('changing');
                }, 300);
            }
        });
    }

    // 🚀 AI智能助手控制
    const applyAITipsBtn = document.getElementById('applyAITips');
    if (applyAITipsBtn) {
        applyAITipsBtn.addEventListener('click', applyAIRecommendations);
    }

    // 初始化AI助手
    initAIAssistant();

    // 🚀 社交分享功能初始化
    setupSocialSharing();

    // 🎮 游戏化排行榜初始化
    initLeaderboard();

    // 📱 移动端手势控制初始化
    initMobileGestures();
}

// 添加事件监听
function setupEventListeners() {
    // 按钮事件
    if (startBtn) startBtn.addEventListener('click', startSimulation);
    if (pauseBtn) pauseBtn.addEventListener('click', pauseSimulation);
    if (resetBtn) resetBtn.addEventListener('click', resetSimulation);

    // 速度控制
    if (speedRange) speedRange.addEventListener('input', updateSpeed);

    // 点数选择
    if (pointsRadios) {
        pointsRadios.forEach(radio => {
            radio.addEventListener('change', updatePointsPerIteration);
        });
    }

    // 主题切换
    if (themeToggle) themeToggle.addEventListener('change', toggleTheme);
    
    // 窗口调整大小事件
    window.addEventListener('resize', resizeCanvas);
    
    // 添加滑动条样式更新
    updateSliderStyles();
    
    // 为所有滑动条添加input事件监听，更新背景色
    document.querySelectorAll('input[type="range"]').forEach(slider => {
        slider.classList.add('color-track');
        updateSliderBackground(slider);
        slider.addEventListener('input', function() {
            updateSliderBackground(this);
        });
    });
}

// 更新滑动条背景
function updateSliderBackground(slider) {
    const min = slider.min || 0;
    const max = slider.max || 100;
    const value = slider.value;
    const percentage = ((value - min) / (max - min)) * 100;
    slider.style.setProperty('--range-progress', `${percentage}%`);
}

// 初始化所有滑动条样式
function updateSliderStyles() {
    document.querySelectorAll('input[type="range"]').forEach(slider => {
        updateSliderBackground(slider);
    });
}

// 调整Canvas大小
function resizeCanvas() {
    if (!simulationCanvas || !convergenceCanvas) return;

    const simulationContainer = simulationCanvas.parentElement;
    const convergenceContainer = convergenceCanvas.parentElement;

    if (!simulationContainer || !convergenceContainer) return;

    // 获取容器的实际尺寸
    const simulationRect = simulationContainer.getBoundingClientRect();
    const convergenceRect = convergenceContainer.getBoundingClientRect();

    // 保持模拟画布为正方形
    const simulationSize = Math.min(simulationRect.width, simulationRect.height);
    
    // 设置CSS尺寸
    simulationCanvas.style.width = `${simulationSize}px`;
    simulationCanvas.style.height = `${simulationSize}px`;
    
    // 设置物理像素尺寸（考虑设备像素比）
    simulationCanvas.width = simulationSize * devicePixelRatio;
    simulationCanvas.height = simulationSize * devicePixelRatio;

    // 重置变换矩阵，避免累积缩放
    simulationCtx.setTransform(1, 0, 0, 1, 0, 0);
    // 缩放上下文以抵消设备像素比
    simulationCtx.scale(devicePixelRatio, devicePixelRatio);

    // 更新画布尺寸和中心点（使用CSS像素）
    canvasSize = simulationSize;
    centerX = canvasSize / 2;
    centerY = canvasSize / 2;
    radius = (canvasSize / 2) * 0.95; // 留一些边距
    
    // 收敛图表画布
    const convergenceWidth = convergenceRect.width;
    const convergenceHeight = Math.min(convergenceRect.height, 300); // 限制最大高度
    
    // 设置CSS尺寸
    convergenceCanvas.style.width = `${convergenceWidth}px`;
    convergenceCanvas.style.height = `${convergenceHeight}px`;
    
    // 设置物理像素尺寸
    convergenceCanvas.width = convergenceWidth * devicePixelRatio;
    convergenceCanvas.height = convergenceHeight * devicePixelRatio;

    // 重置变换矩阵，避免累积缩放
    convergenceCtx.setTransform(1, 0, 0, 1, 0, 0);
    // 缩放上下文
    convergenceCtx.scale(devicePixelRatio, devicePixelRatio);
    
    // 重绘
    drawEmptyCanvas();
    drawChart();
    
    // 调整粒子位置
    initParticles();
}

// 绘制空画布（初始状态）
function drawEmptyCanvas() {
    if (!simulationCtx || !simulationCanvas) return;

    simulationCtx.clearRect(0, 0, simulationCanvas.width, simulationCanvas.height);
    
    // 绘制网格背景
    if (showGrid) {
        drawGrid();
    }
    
    // 绘制正方形边框
    simulationCtx.strokeStyle = isDarkTheme ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.1)';
    simulationCtx.lineWidth = 1 / devicePixelRatio; // 调整线宽
    simulationCtx.strokeRect(0, 0, canvasSize, canvasSize);
    
    // 绘制圆 - 使用渐变效果
    const gradient = simulationCtx.createRadialGradient(
        centerX, centerY, 0,
        centerX, centerY, radius
    );
    
    if (isDarkTheme) {
        gradient.addColorStop(0, 'rgba(99, 102, 241, 0.05)');
        gradient.addColorStop(1, 'rgba(99, 102, 241, 0.01)');
    } else {
        gradient.addColorStop(0, 'rgba(79, 70, 229, 0.05)');
        gradient.addColorStop(1, 'rgba(79, 70, 229, 0.01)');
    }
    
    simulationCtx.beginPath();
    simulationCtx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    simulationCtx.fillStyle = gradient;
    simulationCtx.fill();
    
    // 绘制圆边框
    simulationCtx.strokeStyle = isDarkTheme ? 'rgba(129, 140, 248, 0.5)' : 'rgba(79, 70, 229, 0.4)';
    simulationCtx.lineWidth = 1.5 / devicePixelRatio; // 调整线宽
    simulationCtx.stroke();
    
    // 添加坐标轴
    if (showAxes) {
        drawAxes();
    }
}

// 绘制网格
function drawGrid() {
    const gridSize = canvasSize / 20;
    simulationCtx.strokeStyle = isDarkTheme ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.03)';
    simulationCtx.lineWidth = 0.5 / devicePixelRatio; // 调整线宽
    
    // 水平线
    for (let y = gridSize; y < canvasSize; y += gridSize) {
        simulationCtx.beginPath();
        simulationCtx.moveTo(0, y);
        simulationCtx.lineTo(canvasSize, y);
        simulationCtx.stroke();
    }
    
    // 垂直线
    for (let x = gridSize; x < canvasSize; x += gridSize) {
        simulationCtx.beginPath();
        simulationCtx.moveTo(x, 0);
        simulationCtx.lineTo(x, canvasSize);
        simulationCtx.stroke();
    }
}

// 绘制坐标轴
function drawAxes() {
    simulationCtx.strokeStyle = isDarkTheme ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.2)';
    simulationCtx.lineWidth = 1 / devicePixelRatio; // 调整线宽
    
    // X轴
    simulationCtx.beginPath();
    simulationCtx.moveTo(0, centerY);
    simulationCtx.lineTo(canvasSize, centerY);
    simulationCtx.stroke();
    
    // Y轴
    simulationCtx.beginPath();
    simulationCtx.moveTo(centerX, 0);
    simulationCtx.lineTo(centerX, canvasSize);
    simulationCtx.stroke();
}

// 绘制空图表
function drawEmptyChart() {
    if (!convergenceCtx || !convergenceCanvas) return;

    const width = convergenceCanvas.width / devicePixelRatio;
    const height = convergenceCanvas.height / devicePixelRatio;

    convergenceCtx.clearRect(0, 0, convergenceCanvas.width, convergenceCanvas.height);
    
    // 绘制背景
    convergenceCtx.fillStyle = isDarkTheme ? '#1e293b' : '#f8fafc';
    convergenceCtx.fillRect(0, 0, width, height);
    
    // 绘制网格
    convergenceCtx.strokeStyle = isDarkTheme ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.05)';
    convergenceCtx.lineWidth = 0.5 / devicePixelRatio; // 调整线宽
    
    // 水平网格线
    const yStep = height / 5;
    for (let y = yStep; y < height; y += yStep) {
        convergenceCtx.beginPath();
        convergenceCtx.moveTo(0, y);
        convergenceCtx.lineTo(width, y);
        convergenceCtx.stroke();
    }
    
    // 垂直网格线
    const xStep = width / 10;
    for (let x = xStep; x < width; x += xStep) {
        convergenceCtx.beginPath();
        convergenceCtx.moveTo(x, 0);
        convergenceCtx.lineTo(x, height);
        convergenceCtx.stroke();
    }
    
    // 绘制π的实际值线
    const piY = height / 2;
    convergenceCtx.strokeStyle = isDarkTheme ? 'rgba(236, 72, 153, 0.5)' : 'rgba(236, 72, 153, 0.5)';
    convergenceCtx.lineWidth = 1 / devicePixelRatio; // 调整线宽
    convergenceCtx.setLineDash([5 / devicePixelRatio, 3 / devicePixelRatio]); // 调整虚线间距
    
    convergenceCtx.beginPath();
    convergenceCtx.moveTo(0, piY);
    convergenceCtx.lineTo(width, piY);
    convergenceCtx.stroke();
    
    convergenceCtx.setLineDash([]);
    
    // 添加标签
    convergenceCtx.fillStyle = isDarkTheme ? '#cbd5e1' : '#64748b';
    convergenceCtx.font = `${12 / devicePixelRatio}px sans-serif`; // 调整字体大小
    convergenceCtx.textAlign = 'right';
    convergenceCtx.fillText(`π = ${REAL_PI_VALUE.toFixed(8)}`, width - 10, piY - 5);
}

// 清除图表
function clearChart() {
    convergenceData = [];
    drawEmptyChart();

    // 添加动画效果
    if (clearChartBtn) {
        clearChartBtn.classList.add('active');
        setTimeout(() => {
            clearChartBtn.classList.remove('active');
        }, 300);
    }
}

// 绘制图表
function drawChart() {
    if (convergenceData.length <= 1) return;
    
    const width = convergenceCanvas.width / devicePixelRatio;
    const height = convergenceCanvas.height / devicePixelRatio;
    
    // 清除并重绘空图表
    drawEmptyChart();
    
    // 计算缩放比例
    const xScale = width / (convergenceData.length - 1);
    const yScale = height / 4; // 假设π值在2-4之间，居中显示
    const yOffset = height / 2;
    
    // 绘制线条
    convergenceCtx.strokeStyle = isDarkTheme ? '#818cf8' : '#4f46e5';
    convergenceCtx.lineWidth = 2 / devicePixelRatio; // 调整线宽
    convergenceCtx.lineJoin = 'round';
    
    convergenceCtx.beginPath();
    convergenceCtx.moveTo(0, yOffset - (convergenceData[0] - 3) * yScale);
    
    for (let i = 1; i < convergenceData.length; i++) {
        const x = i * xScale;
        const y = yOffset - (convergenceData[i] - 3) * yScale;
        convergenceCtx.lineTo(x, y);
    }
    
    convergenceCtx.stroke();
    
    // 绘制最后一个点
    const lastX = (convergenceData.length - 1) * xScale;
    const lastY = yOffset - (convergenceData[convergenceData.length - 1] - 3) * yScale;
    
    convergenceCtx.fillStyle = isDarkTheme ? '#ec4899' : '#db2777';
    convergenceCtx.beginPath();
    convergenceCtx.arc(lastX, lastY, 4 / devicePixelRatio, 0, 2 * Math.PI); // 调整点大小
    convergenceCtx.fill();
    
    // 添加发光效果
    convergenceCtx.shadowColor = isDarkTheme ? 'rgba(236, 72, 153, 0.6)' : 'rgba(219, 39, 119, 0.6)';
    convergenceCtx.shadowBlur = 10 / devicePixelRatio; // 调整阴影模糊度
    convergenceCtx.beginPath();
    convergenceCtx.arc(lastX, lastY, 4 / devicePixelRatio, 0, 2 * Math.PI);
    convergenceCtx.fill();
    convergenceCtx.shadowBlur = 0;
}

// 初始化粒子
function initParticles() {
    // 粒子已通过HTML和CSS实现，这里可以添加额外的动态粒子
}

// 生成随机点
function generateRandomPoint() {
    // 生成随机坐标 (范围从-1到1)
    const x = Math.random() * 2 - 1;
    const y = Math.random() * 2 - 1;
    
    // 检查点是否在圆内 (x^2 + y^2 <= 1)
    const inCircle = x * x + y * y <= 1;
    
    // 将坐标转换为画布坐标
    // 注意：这里的canvasX和canvasY需要基于原始的canvasSize计算，因为ctx已经被scale
    const canvasX = (x + 1) * canvasSize / 2;
    const canvasY = (y + 1) * canvasSize / 2;
    
    return { x: canvasX, y: canvasY, inCircle };
}

// 绘制点
function drawPoint(x, y, inCircle) {
    // 设置点的颜色
    simulationCtx.fillStyle = inCircle ? 
        (isDarkTheme ? '#fb7185' : '#f87171') : 
        (isDarkTheme ? '#60a5fa' : '#60a5fa');
    
    // 添加发光效果
    simulationCtx.shadowColor = inCircle ? 
        (isDarkTheme ? 'rgba(251, 113, 133, 0.6)' : 'rgba(248, 113, 113, 0.6)') : 
        (isDarkTheme ? 'rgba(96, 165, 250, 0.6)' : 'rgba(96, 165, 250, 0.6)');
    simulationCtx.shadowBlur = 5 / devicePixelRatio; // 调整阴影模糊度
    
    // 绘制圆形点
    simulationCtx.beginPath();
    simulationCtx.arc(x, y, pointRadius / devicePixelRatio, 0, 2 * Math.PI); // 调整点大小
    simulationCtx.fill();
    
    // 重置阴影
    simulationCtx.shadowBlur = 0;
}

// 更新统计数据
function updateStats() {
    // 计算π的估算值
    const piEstimate = totalPoints > 0 ? (4 * circlePoints / totalPoints) : 0;
    const percentage = totalPoints > 0 ? ((circlePoints / totalPoints) * 100).toFixed(2) : 0;
    const errorPercentage = Math.abs((piEstimate - REAL_PI_VALUE) / REAL_PI_VALUE * 100).toFixed(2);
    const accuracy = Math.max(0, 100 - parseFloat(errorPercentage)).toFixed(2);
    
    // 添加动画效果的函数（增强版）
    const animateElement = (element, value, prefix = '', suffix = '') => {
        if (!element) return; // 确保元素存在
        
        const oldValue = element.textContent.replace(prefix, '').replace(suffix, '');
        const newValue = value.toString();
        
        // 检查是否是重大变化
        if (oldValue && Math.abs(parseFloat(newValue) - parseFloat(oldValue)) > 0.1) {
            element.classList.add('major-change');
            setTimeout(() => element.classList.remove('major-change'), 1500);
        }
        
        element.classList.add('changing');
        element.textContent = prefix + value + suffix;
        setTimeout(() => {
            element.classList.remove('changing');
        }, 300);
    };
    
    // 更新显示
    animateElement(totalPointsElement, totalPoints.toLocaleString());
    animateElement(circlePointsElement, circlePoints.toLocaleString());
    animateElement(percentageElement, percentage, '', '%');
    animateElement(piValueElement, piEstimate.toFixed(8));
    animateElement(piValueOverlayElement, piEstimate.toFixed(8));
    animateElement(errorElement, errorPercentage, '', '%');
    
    // 更新精确度条
    if (accuracyBar && accuracyValue) {
        const currentAccuracy = parseFloat(accuracy);
        accuracyBar.style.width = `${accuracy}%`;
        accuracyValue.textContent = `${accuracy}%`;
        
        // 🚀 国奖级成就系统检查
        checkAchievements(currentAccuracy, totalPoints);
        
        // 🤖 AI智能分析（每1000点分析一次）
        if (totalPoints % 1000 === 0 && totalPoints > 0) {
            runAIAnalysis(currentAccuracy, totalPoints, errorPercentage, speed);
        }

        // 🎮 更新排行榜（每500点更新一次）
        if (totalPoints % 500 === 0 && totalPoints > 0) {
            updateRealLeaderboard();
        }

        // 📊 记录模拟数据（每1000点记录一次）
        if (totalPoints % 1000 === 0 && totalPoints > 0) {
            recordSimulationCompletion();
        }
        
        // 根据精确度设置颜色和特效
        if (currentAccuracy > 95) {
            accuracyBar.style.background = 'var(--success-color)';
            if (currentAccuracy > achievementSystem.lastAccuracy + 1) {
                accuracyBar.classList.add('breakthrough');
                setTimeout(() => accuracyBar.classList.remove('breakthrough'), 2000);
            }
        } else if (currentAccuracy > 80) {
            accuracyBar.style.background = 'var(--warning-color)';
        } else {
            accuracyBar.style.background = 'var(--danger-color)';
        }
        
        achievementSystem.lastAccuracy = currentAccuracy;
    }
    
    // 更新最佳估计值
    if (bestEstimateElement && (Math.abs(piEstimate - REAL_PI_VALUE) < Math.abs(bestPiEstimate - REAL_PI_VALUE) || bestPiEstimate === 0)) {
        bestPiEstimate = piEstimate;
        animateElement(bestEstimateElement, bestPiEstimate.toFixed(8));
    }
    
    // 更新收敛速度
    if (convergenceSpeedElement) {
        // Check if this is an interval where convergenceData is (or was just) updated
        const isIntervalBoundaryForConvergenceData = (totalPoints > 0 && (totalPoints % 100 === 0 || totalPoints <= 100));

        if (isIntervalBoundaryForConvergenceData && convergenceData.length > 0) {
            // piEstimate is the value for the current totalPoints (which will be pushed to convergenceData shortly)
            // convergenceData[convergenceData.length - 1] is the piEstimate from the end of the previous data interval
            const currentPiForIntervalEnd = piEstimate; 
            const piAtPreviousIntervalEnd = convergenceData[convergenceData.length - 1];
            
            const rawRateOfChange = Math.abs(currentPiForIntervalEnd - piAtPreviousIntervalEnd);
            convergenceSpeed = rawRateOfChange; // Update global numeric variable

            let displayedSpeed;
            if (rawRateOfChange === 0) {
                displayedSpeed = "0.000000"; 
            } else if (rawRateOfChange < 0.000001 && rawRateOfChange !== 0) { // Ensure not exactly zero for exponential
                displayedSpeed = rawRateOfChange.toExponential(2); // Use scientific notation for very small non-zero changes
            } else {
                displayedSpeed = rawRateOfChange.toFixed(6); // Standard display
            }
            animateElement(convergenceSpeedElement, displayedSpeed);
        } else if (isIntervalBoundaryForConvergenceData && convergenceData.length === 0) {
            // This is the first data interval boundary. No previous data for comparison.
            // resetSimulation() already set the textContent to '-', which is correct.
            // We ensure the numeric convergenceSpeed is 0.
            convergenceSpeed = 0;
        }
        // If not an interval boundary where convergenceData is updated, 
        // the convergenceSpeedElement retains its last displayed value, which is appropriate.
        // The initial '-' is handled by resetSimulation.
    }
    
    // 更新收敛图表
    if (totalPoints % 100 === 0 || totalPoints <= 100) {
        convergenceData.push(piEstimate);
        drawChart();

        // 记录历史数据 - 更频繁地记录
        if (totalPoints % 500 === 0 && totalPoints > 0) {
            const historyRecord = {
                timestamp: Date.now(),
                totalPoints: totalPoints,
                circlePoints: circlePoints,
                piEstimate: piEstimate,
                error: parseFloat(errorPercentage),
                accuracy: parseFloat(accuracy),
                duration: Date.now() - (simulationHistory.length > 0 ? simulationHistory[simulationHistory.length - 1].timestamp : Date.now())
            };
            simulationHistory.push(historyRecord);

            // 限制历史记录数量
            if (simulationHistory.length > 50) {
                simulationHistory = simulationHistory.slice(-50);
            }

            // 如果在分析页面，实时更新历史表格
            if (currentPage === 'analysis') {
                updateHistoryTable();
            }
        }
    }
}

// 模拟步骤
function simulationStep() {
    for (let i = 0; i < pointsPerIteration; i++) {
        const point = generateRandomPoint();
        drawPoint(point.x, point.y, point.inCircle);
        
        // 将点添加到points数组中
        points.push({
            x: point.x,
            y: point.y,
            inCircle: point.inCircle
        });
        
        // 限制points数组大小以避免内存问题（保留最近的5000个点）
        if (points.length > 5000) {
            points.shift();
        }
        
        totalPoints++;
        if (point.inCircle) {
            circlePoints++;
        }
    }
    
    updateStats();
    
    if (isRunning) {
        animationId = requestAnimationFrame(simulationStep);
    }
}

// 开始模拟
function startSimulation() {
    if (!isRunning) {
        isRunning = true;
        startBtn.classList.add('active');
        pauseBtn.classList.remove('active');
        
        // 记录模拟开始时间（仅在新模拟开始时）
        if (points.length === 0) {
            simulationStartTime = Date.now();
        }
        
        // 添加动画效果
        startBtn.classList.add('active');
        setTimeout(() => {
            startBtn.classList.remove('active');
        }, 300);
        
        animationId = requestAnimationFrame(simulationStep);
    }
}

// 暂停模拟
function pauseSimulation() {
    if (isRunning) {
        isRunning = false;
        startBtn.classList.remove('active');
        pauseBtn.classList.add('active');
        
        // 添加动画效果
        pauseBtn.classList.add('active');
        setTimeout(() => {
            pauseBtn.classList.remove('active');
        }, 300);
        
        if (animationId !== null) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
    }
}

// 重置模拟
function resetSimulation() {
    // 停止动画
    if (isRunning) {
        pauseSimulation();
    }
    
    // 添加动画效果
    resetBtn.classList.add('active');
    setTimeout(() => {
        resetBtn.classList.remove('active');
    }, 300);
    
    // 重置变量
    totalPoints = 0;
    circlePoints = 0;
    points = []; // 重置模拟点数组
    convergenceData = [];
    bestPiEstimate = 0;
    convergenceSpeed = 0;
    
    // 重绘画布
    drawEmptyCanvas();
    drawEmptyChart();
    
    // 更新统计数据
    updateStats();
    
    // 重置统计面板
    if (bestEstimateElement) bestEstimateElement.textContent = '-';
    if (convergenceSpeedElement) convergenceSpeedElement.textContent = '-';
}

// 更新速度
function updateSpeed() {
    speed = parseInt(speedRange.value);
    speedValue.textContent = speed;
    
    // 添加动画效果
    speedValue.classList.add('changing');
    setTimeout(() => {
        speedValue.classList.remove('changing');
    }, 300);
    
    // 更新滑动条背景
    updateSliderBackground(speedRange);
}

// 更新每次迭代点数
function updatePointsPerIteration() {
    pointsPerIteration = parseInt(document.querySelector('input[name="pointsPerIteration"]:checked').value);
}

// 切换主题
function toggleTheme() {
    isDarkTheme = themeToggle.checked;
    
    if (isDarkTheme) {
        document.documentElement.setAttribute('data-theme', 'dark');
    } else {
        document.documentElement.removeAttribute('data-theme');
    }
    
    // 保存主题设置到本地存储
    localStorage.setItem('theme', isDarkTheme ? 'dark' : 'light');
    
    // 重绘画布
    drawEmptyCanvas();
    drawChart();
}

// 检查主题偏好
function checkThemePreference() {
    const savedTheme = localStorage.getItem('theme');
    
    if (savedTheme === 'dark') {
        themeToggle.checked = true;
        isDarkTheme = true;
        document.documentElement.setAttribute('data-theme', 'dark');
    } else {
        themeToggle.checked = false;
        isDarkTheme = false;
        document.documentElement.removeAttribute('data-theme');
    }
}

// 添加动画类
function addAnimationClasses() {
    document.querySelectorAll('.card').forEach((card, index) => {
        card.classList.add('fade-in', 'enhanced-card');
        card.style.animationDelay = `${index * 0.1}s`;
    });

    // 添加交互式涟漪效果
    addRippleEffects();

    // 添加浮动粒子
    addFloatingParticles();

    // 添加数据流动画
    addDataStreamAnimations();
}

// 添加涟漪效果
function addRippleEffects() {
    document.querySelectorAll('.btn, .nav-item, .feature-card').forEach(element => {
        element.classList.add('ripple-container');

        element.addEventListener('click', function(e) {
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;

            ripple.style.width = ripple.style.height = size + 'px';
            ripple.style.left = x + 'px';
            ripple.style.top = y + 'px';
            ripple.classList.add('ripple');

            this.appendChild(ripple);

            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
}

// 添加浮动粒子
function addFloatingParticles() {
    const containers = document.querySelectorAll('.welcome-hero, .simulation-card, .analysis-card');

    containers.forEach(container => {
        for (let i = 0; i < 5; i++) {
            const particle = document.createElement('div');
            particle.classList.add('particle-enhanced');
            particle.style.width = Math.random() * 6 + 3 + 'px';
            particle.style.height = particle.style.width;
            particle.style.left = Math.random() * 100 + '%';
            particle.style.top = Math.random() * 100 + '%';
            particle.style.background = `rgba(var(--primary-color-rgb), ${Math.random() * 0.5 + 0.2})`;
            particle.style.animationDelay = Math.random() * 6 + 's';

            container.appendChild(particle);
        }
    });
}

// 添加数据流动画
function addDataStreamAnimations() {
    const visualizationContainers = document.querySelectorAll('.canvas-wrapper, .chart-container');

    visualizationContainers.forEach(container => {
        container.classList.add('data-visualization');

        for (let i = 0; i < 8; i++) {
            const stream = document.createElement('div');
            stream.classList.add('data-stream');
            stream.style.left = Math.random() * 100 + '%';
            stream.style.animationDelay = Math.random() * 3 + 's';
            stream.style.animationDuration = (Math.random() * 2 + 2) + 's';

            container.appendChild(stream);
        }
    });
}

// 增强的鼠标跟踪效果
function addMouseTrackingEffects() {
    let mouseX = 0;
    let mouseY = 0;

    document.addEventListener('mousemove', (e) => {
        mouseX = e.clientX;
        mouseY = e.clientY;

        // 更新CSS变量用于鼠标跟踪效果
        document.documentElement.style.setProperty('--mouse-x', mouseX + 'px');
        document.documentElement.style.setProperty('--mouse-y', mouseY + 'px');
    });

    // 为特定元素添加鼠标跟踪效果
    document.querySelectorAll('.hero-logo, .mega-pi-symbol').forEach(element => {
        element.addEventListener('mousemove', (e) => {
            const rect = element.getBoundingClientRect();
            const x = e.clientX - rect.left - rect.width / 2;
            const y = e.clientY - rect.top - rect.height / 2;

            element.style.transform = `translate(${x * 0.1}px, ${y * 0.1}px) scale(1.05)`;
        });

        element.addEventListener('mouseleave', () => {
            element.style.transform = 'translate(0, 0) scale(1)';
        });
    });
}

// 性能优化的动画控制
function optimizeAnimations() {
    // 检测用户是否偏好减少动画
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    if (prefersReducedMotion) {
        document.documentElement.style.setProperty('--animation-duration', '0.1s');
        document.documentElement.style.setProperty('--transition-duration', '0.1s');
    }

    // 在页面不可见时暂停动画
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            document.body.style.animationPlayState = 'paused';
        } else {
            document.body.style.animationPlayState = 'running';
        }
    });
}

// 页面导航功能
function setupPageNavigation() {
    // 设置导航项点击事件
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            const targetPage = item.dataset.page;
            if (targetPage && targetPage !== currentPage) {
                navigateToPage(targetPage);
            }
        });
    });

    // 设置导航按钮点击事件
    navigateButtons.forEach(button => {
        button.addEventListener('click', () => {
            const targetPage = button.dataset.navigate;
            if (targetPage && targetPage !== currentPage) {
                navigateToPage(targetPage);
            }
        });
    });

    // 初始显示欢迎页面
    showPage('welcome');

    // 添加键盘导航支持
    setupKeyboardNavigation();
}

// 键盘导航支持
function setupKeyboardNavigation() {
    document.addEventListener('keydown', (e) => {
        // Alt + 数字键快速切换页面
        if (e.altKey) {
            switch(e.key) {
                case '1':
                    e.preventDefault();
                    navigateToPage('welcome');
                    break;
                case '2':
                    e.preventDefault();
                    navigateToPage('simulation');
                    break;
                case '3':
                    e.preventDefault();
                    navigateToPage('analysis');
                    break;
            }
        }

        // 空格键控制模拟
        if (e.code === 'Space' && currentPage === 'simulation') {
            e.preventDefault();
            if (isRunning) {
                pauseSimulation();
            } else {
                startSimulation();
            }
        }

        // R键重置模拟
        if (e.key === 'r' && currentPage === 'simulation') {
            e.preventDefault();
            resetSimulation();
        }

        // Escape键暂停模拟
        if (e.key === 'Escape' && isRunning) {
            pauseSimulation();
        }
    });

    // 添加键盘提示
    const keyboardHints = document.createElement('div');
    keyboardHints.className = 'keyboard-hints';
    keyboardHints.innerHTML = `
        <div class="hint-item">Alt+1: 首页</div>
        <div class="hint-item">Alt+2: 模拟</div>
        <div class="hint-item">Alt+3: 分析</div>
        <div class="hint-item">空格: 开始/暂停</div>
        <div class="hint-item">R: 重置</div>
    `;
    keyboardHints.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: var(--glass-background);
        backdrop-filter: blur(10px);
        border: var(--glass-border);
        border-radius: var(--border-radius);
        padding: 10px;
        font-size: 0.8rem;
        opacity: 0;
        transform: translateY(20px);
        transition: all 0.3s ease;
        z-index: 1000;
        pointer-events: none;
    `;

    document.body.appendChild(keyboardHints);

    // 显示/隐藏键盘提示
    let hintTimeout;
    document.addEventListener('keydown', () => {
        keyboardHints.style.opacity = '1';
        keyboardHints.style.transform = 'translateY(0)';

        clearTimeout(hintTimeout);
        hintTimeout = setTimeout(() => {
            keyboardHints.style.opacity = '0';
            keyboardHints.style.transform = 'translateY(20px)';
        }, 3000);
    });
}

function navigateToPage(targetPage) {
    if (isNavigating) return;

    isNavigating = true;
    const currentPageElement = document.getElementById(`${currentPage}-page`);
    const targetPageElement = document.getElementById(`${targetPage}-page`);

    if (!targetPageElement) {
        console.error(`Page ${targetPage} not found`);
        isNavigating = false;
        return;
    }

    // 更新导航栏状态
    updateNavigation(targetPage);

    // 页面切换动画
    if (currentPageElement) {
        currentPageElement.classList.add('leaving');
        setTimeout(() => {
            currentPageElement.classList.remove('active', 'leaving');
        }, 300);
    }

    // 显示目标页面
    setTimeout(() => {
        targetPageElement.classList.add('entering');
        targetPageElement.classList.add('active');

        setTimeout(() => {
            targetPageElement.classList.remove('entering');
            isNavigating = false;
        }, 300);

        // 页面特定的初始化
        onPageEnter(targetPage);
    }, 150);

    currentPage = targetPage;
}

function showPage(pageName) {
    // 隐藏所有页面
    pageContainers.forEach(page => {
        page.classList.remove('active');
    });

    // 显示目标页面
    const targetPage = document.getElementById(`${pageName}-page`);
    if (targetPage) {
        targetPage.classList.add('active');
        currentPage = pageName;
        updateNavigation(pageName);
        onPageEnter(pageName);
    }
}

function updateNavigation(activePage) {
    navItems.forEach(item => {
        item.classList.remove('active');
        if (item.dataset.page === activePage) {
            item.classList.add('active');
        }
    });
}

function onPageEnter(pageName) {
    // 添加加载状态
    const pageElement = document.getElementById(`${pageName}-page`);
    if (pageElement) {
        pageElement.classList.add('loading');

        setTimeout(() => {
            pageElement.classList.remove('loading');
        }, 500);
    }

    switch(pageName) {
        case 'welcome':
            // 欢迎页面进入时的处理
            animateWelcomeElements();
            break;
        case 'simulation':
            // 模拟页面进入时的处理
            setTimeout(() => {
                // 延迟初始化以确保DOM元素已加载
                if (simulationCanvas && convergenceCanvas) {
                    setupCanvas();
                    resizeCanvas();
                    drawEmptyCanvas();
                    drawEmptyChart();
                    initParticles();
                }
                animateSimulationElements();
            }, 100);
            break;
        case 'analysis':
            // 分析页面进入时的处理
            initAnalysisPage();
            animateAnalysisElements();
            break;
        case 'tutorial':
            // 教学页面进入时的处理
            initTutorialDemo();
            break;
        case '3d-visualization':
            // 3D可视化页面（开发中）
            showDevelopmentStatus('3D可视化');
            break;
        case 'comparison':
            // 算法对比页面
            initAlgorithmComparison();
            break;
        case 'achievements':
            // 成就中心页面
            const userData = DataManager.getUserData();
            updateAchievementsPage(userData);
            break;
    }
}

// 动画化欢迎页面元素
function animateWelcomeElements() {
    const elements = document.querySelectorAll('.welcome-hero .hero-content > *');
    elements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(30px)';

        setTimeout(() => {
            el.style.transition = 'all 0.6s cubic-bezier(0.22, 1, 0.36, 1)';
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, index * 200);
    });
}

// 动画化模拟页面元素
function animateSimulationElements() {
    const cards = document.querySelectorAll('.simulation-page .card, .simulation-page .glass');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'scale(0.9) translateY(20px)';

        setTimeout(() => {
            card.style.transition = 'all 0.5s cubic-bezier(0.22, 1, 0.36, 1)';
            card.style.opacity = '1';
            card.style.transform = 'scale(1) translateY(0)';
        }, index * 100);
    });
}

// 动画化分析页面元素
function animateAnalysisElements() {
    const cards = document.querySelectorAll('.analysis-page .analysis-card');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateX(-30px)';

        setTimeout(() => {
            card.style.transition = 'all 0.6s cubic-bezier(0.22, 1, 0.36, 1)';
            card.style.opacity = '1';
            card.style.transform = 'translateX(0)';
        }, index * 150);
    });
}

// 初始化粒子背景
function initParticlesBackground() {
    const particlesContainer = document.getElementById('particles-js');
    if (typeof particlesJS !== 'undefined' && particlesContainer) {
        particlesJS('particles-js', {
            particles: {
                number: { value: 80, density: { enable: true, value_area: 800 } },
                color: { value: getComputedStyle(document.documentElement).getPropertyValue('--primary-color') },
                shape: { type: 'circle' },
                opacity: { value: 0.5, random: false },
                size: { value: 3, random: true },
                line_linked: {
                    enable: true,
                    distance: 150,
                    color: getComputedStyle(document.documentElement).getPropertyValue('--primary-color'),
                    opacity: 0.4,
                    width: 1
                },
                move: {
                    enable: true,
                    speed: 2,
                    direction: 'none',
                    random: false,
                    straight: false,
                    out_mode: 'out',
                    bounce: false
                }
            },
            interactivity: {
                detect_on: 'canvas',
                events: {
                    onhover: { enable: true, mode: 'repulse' },
                    onclick: { enable: true, mode: 'push' },
                    resize: true
                }
            },
            retina_detect: true
        });
    } else {
        // Fallback: create simple CSS particles if particles.js is not available
        if (particlesContainer) {
            particlesContainer.style.background = 'radial-gradient(circle at 20% 50%, rgba(var(--primary-color-rgb), 0.1) 0%, transparent 50%), radial-gradient(circle at 80% 20%, rgba(var(--accent-color-rgb), 0.1) 0%, transparent 50%)';
        }
    }
}

// 初始化分析页面
function initAnalysisPage() {
    // 如果没有历史数据，添加一些示例数据
    if (simulationHistory.length === 0) {
        addSampleHistoryData();
    }

    updateAnalysisStats();
    initAnalysisChart();
    updateHistoryTable();
    setupAnalysisControls();
}

// 添加示例历史数据
function addSampleHistoryData() {
    const sampleData = [
        { totalPoints: 1000, piEstimate: 3.144, error: 0.07, accuracy: 99.93 },
        { totalPoints: 2000, piEstimate: 3.141, error: 0.02, accuracy: 99.98 },
        { totalPoints: 3000, piEstimate: 3.1416, error: 0.00, accuracy: 100.00 },
        { totalPoints: 4000, piEstimate: 3.1415, error: 0.00, accuracy: 100.00 },
        { totalPoints: 5000, piEstimate: 3.1412, error: 0.01, accuracy: 99.99 }
    ];

    const baseTime = Date.now() - (sampleData.length * 30000); // 30秒间隔

    sampleData.forEach((data, index) => {
        const historyRecord = {
            timestamp: baseTime + (index * 30000),
            totalPoints: data.totalPoints,
            circlePoints: Math.round(data.totalPoints * data.piEstimate / 4),
            piEstimate: data.piEstimate,
            error: data.error,
            accuracy: data.accuracy,
            duration: 30000
        };
        simulationHistory.push(historyRecord);
    });
}

// 更新分析统计数据
function updateAnalysisStats() {
    const totalSimulationsElement = document.getElementById('totalSimulations');
    const bestAccuracyElement = document.getElementById('bestAccuracy');
    const avgConvergenceTimeElement = document.getElementById('avgConvergenceTime');
    const convergenceRateElement = document.getElementById('convergenceRate');

    if (totalSimulationsElement) {
        totalSimulationsElement.textContent = simulationHistory.length;
    }

    if (bestAccuracyElement && simulationHistory.length > 0) {
        const bestAccuracy = Math.max(...simulationHistory.map(h => h.accuracy));
        bestAccuracyElement.textContent = `${bestAccuracy.toFixed(2)}%`;
    }

    if (avgConvergenceTimeElement && simulationHistory.length > 0) {
        const avgTime = simulationHistory.reduce((sum, h) => sum + h.duration, 0) / simulationHistory.length;
        avgConvergenceTimeElement.textContent = `${(avgTime / 1000).toFixed(1)}s`;
    }

    if (convergenceRateElement) {
        convergenceRateElement.textContent = convergenceSpeed.toFixed(6);
    }
}

// 初始化分析图表
function initAnalysisChart() {
    const canvas = document.getElementById('analysisChart');
    if (!canvas) return;

    const container = canvas.parentElement;
    const ctx = canvas.getContext('2d');

    // 设置画布尺寸以充满容器
    const containerRect = container.getBoundingClientRect();
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.width = containerRect.width * devicePixelRatio;
    canvas.height = containerRect.height * devicePixelRatio;
    ctx.scale(devicePixelRatio, devicePixelRatio);

    drawAnalysisChart(ctx, 'convergence');
}

// 绘制分析图表
function drawAnalysisChart(ctx, chartType) {
    const width = ctx.canvas.width / devicePixelRatio;
    const height = ctx.canvas.height / devicePixelRatio;

    ctx.clearRect(0, 0, width, height);

    // 绘制背景
    ctx.fillStyle = isDarkTheme ? '#1e293b' : '#f8fafc';
    ctx.fillRect(0, 0, width, height);

    // 绘制网格
    ctx.strokeStyle = isDarkTheme ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.05)';
    ctx.lineWidth = 0.5;

    // 水平网格线
    for (let y = 0; y < height; y += height / 10) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(width, y);
        ctx.stroke();
    }

    // 垂直网格线
    for (let x = 0; x < width; x += width / 10) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, height);
        ctx.stroke();
    }

    // 根据图表类型绘制不同的内容
    switch(chartType) {
        case 'convergence':
            drawConvergenceChart(ctx, width, height);
            break;
        case 'error':
            drawErrorChart(ctx, width, height);
            break;
        case 'distribution':
            drawDistributionChart(ctx, width, height);
            break;
        case 'comparison':
            drawComparisonChart(ctx, width, height);
            break;
    }
}

// 绘制收敛图表
function drawConvergenceChart(ctx, width, height) {
    if (convergenceData.length <= 1) return;

    const xScale = width / (convergenceData.length - 1);
    const yScale = height / 4;
    const yOffset = height / 2;

    ctx.strokeStyle = isDarkTheme ? '#818cf8' : '#4f46e5';
    ctx.lineWidth = 2;
    ctx.lineJoin = 'round';

    ctx.beginPath();
    ctx.moveTo(0, yOffset - (convergenceData[0] - 3) * yScale);

    for (let i = 1; i < convergenceData.length; i++) {
        const x = i * xScale;
        const y = yOffset - (convergenceData[i] - 3) * yScale;
        ctx.lineTo(x, y);
    }

    ctx.stroke();

    // 绘制π的真实值线
    const piY = yOffset - (REAL_PI_VALUE - 3) * yScale;
    ctx.strokeStyle = isDarkTheme ? 'rgba(236, 72, 153, 0.5)' : 'rgba(236, 72, 153, 0.5)';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 3]);

    ctx.beginPath();
    ctx.moveTo(0, piY);
    ctx.lineTo(width, piY);
    ctx.stroke();

    ctx.setLineDash([]);
}

// 绘制误差图表
function drawErrorChart(ctx, width, height) {
    if (simulationHistory.length <= 1) return;

    const xScale = width / (simulationHistory.length - 1);
    const maxError = Math.max(...simulationHistory.map(h => h.error));
    const yScale = height / maxError;

    ctx.strokeStyle = isDarkTheme ? '#f87171' : '#ef4444';
    ctx.lineWidth = 2;
    ctx.lineJoin = 'round';

    ctx.beginPath();
    ctx.moveTo(0, height - simulationHistory[0].error * yScale);

    for (let i = 1; i < simulationHistory.length; i++) {
        const x = i * xScale;
        const y = height - simulationHistory[i].error * yScale;
        ctx.lineTo(x, y);
    }

    ctx.stroke();
}

// 绘制分布图表
function drawDistributionChart(ctx, width, height) {
    if (simulationHistory.length <= 1) return;

    const barWidth = width / simulationHistory.length;
    const maxAccuracy = Math.max(...simulationHistory.map(h => h.accuracy));
    const yScale = height / maxAccuracy;

    ctx.fillStyle = isDarkTheme ? '#34d399' : '#10b981';

    simulationHistory.forEach((record, index) => {
        const x = index * barWidth;
        const barHeight = record.accuracy * yScale;
        const y = height - barHeight;

        ctx.fillRect(x, y, barWidth - 1, barHeight);
    });
}

// 绘制对比图表
function drawComparisonChart(ctx, width, height) {
    if (convergenceData.length <= 1) return;

    const xScale = width / (convergenceData.length - 1);
    const yScale = height / 4;
    const yOffset = height / 2;

    // 绘制实际收敛曲线
    ctx.strokeStyle = isDarkTheme ? '#818cf8' : '#4f46e5';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(0, yOffset - (convergenceData[0] - 3) * yScale);

    for (let i = 1; i < convergenceData.length; i++) {
        const x = i * xScale;
        const y = yOffset - (convergenceData[i] - 3) * yScale;
        ctx.lineTo(x, y);
    }
    ctx.stroke();

    // 绘制理论收敛曲线（简化版）
    ctx.strokeStyle = isDarkTheme ? 'rgba(34, 197, 94, 0.7)' : 'rgba(34, 197, 94, 0.7)';
    ctx.lineWidth = 1;
    ctx.setLineDash([3, 3]);
    ctx.beginPath();

    for (let i = 0; i < convergenceData.length; i++) {
        const x = i * xScale;
        const theoreticalValue = REAL_PI_VALUE + (Math.random() - 0.5) * 0.1 / Math.sqrt(i + 1);
        const y = yOffset - (theoreticalValue - 3) * yScale;

        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.stroke();
    ctx.setLineDash([]);
}

// 更新历史记录表格
function updateHistoryTable() {
    const tableBody = document.getElementById('historyTableBody');
    if (!tableBody) return;

    tableBody.innerHTML = '';

    simulationHistory.slice(-10).reverse().forEach(record => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${new Date(record.timestamp).toLocaleTimeString()}</td>
            <td>${record.totalPoints.toLocaleString()}</td>
            <td>${record.piEstimate.toFixed(8)}</td>
            <td>${record.error.toFixed(4)}%</td>
            <td>${record.accuracy.toFixed(2)}%</td>
        `;
        tableBody.appendChild(row);
    });
}

// 设置分析页面控件
function setupAnalysisControls() {
    const chartTypeSelect = document.getElementById('chartTypeSelect');
    const clearHistoryBtn = document.getElementById('clearHistoryBtn');
    const exportDataBtn = document.getElementById('exportDataBtn');

    if (chartTypeSelect) {
        chartTypeSelect.addEventListener('change', (e) => {
            const canvas = document.getElementById('analysisChart');
            if (canvas) {
                const ctx = canvas.getContext('2d');
                drawAnalysisChart(ctx, e.target.value);
            }
        });
    }

    if (clearHistoryBtn) {
        clearHistoryBtn.addEventListener('click', () => {
            simulationHistory = [];
            updateHistoryTable();
            updateAnalysisStats();
        });
    }

    if (exportDataBtn) {
        exportDataBtn.addEventListener('click', exportSimulationData);
    }
}

// 导出模拟数据
function exportSimulationData() {
    const data = {
        simulationHistory,
        convergenceData,
        currentStats: {
            totalPoints,
            circlePoints,
            piEstimate: totalPoints > 0 ? (4 * circlePoints / totalPoints) : 0,
            error: totalPoints > 0 ? Math.abs((4 * circlePoints / totalPoints) - REAL_PI_VALUE) / REAL_PI_VALUE * 100 : 0
        }
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `monte-carlo-pi-data-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 错误处理和调试功能
function setupErrorHandling() {
    // 全局错误处理
    window.addEventListener('error', (e) => {
        if (e.error) {
        console.error('Global error:', e.error);
            console.error('Error details:', {
                message: e.message,
                filename: e.filename,
                lineno: e.lineno,
                colno: e.colno,
                error: e.error
            });
        } else {
            console.warn('Global error event with null error:', {
                message: e.message,
                filename: e.filename,
                lineno: e.lineno,
                colno: e.colno
            });
        }
        showErrorMessage('发生了一个错误，请刷新页面重试');
    });

    // Promise 错误处理
    window.addEventListener('unhandledrejection', (e) => {
        console.error('Unhandled promise rejection:', e.reason);
        showErrorMessage('操作失败，请重试');
    });
}

// 显示错误消息
function showErrorMessage(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-toast';
    errorDiv.textContent = message;
    errorDiv.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: var(--danger-color);
        color: white;
        padding: 12px 20px;
        border-radius: var(--border-radius);
        box-shadow: var(--shadow-lg);
        z-index: 10000;
        animation: slideInRight 0.3s ease;
    `;

    document.body.appendChild(errorDiv);

    setTimeout(() => {
        errorDiv.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 300);
    }, 3000);
}

// 性能监控
function setupPerformanceMonitoring() {
    if ('performance' in window) {
        window.addEventListener('load', () => {
            setTimeout(() => {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('Page load time:', perfData.loadEventEnd - perfData.loadEventStart, 'ms');

                // 如果加载时间过长，显示提示
                if (perfData.loadEventEnd - perfData.loadEventStart > 3000) {
                    console.warn('Page load time is slow');
                }
            }, 0);
        });
    }
}

// 兼容性检查
function checkCompatibility() {
    const features = {
        'CSS Grid': 'grid' in document.createElement('div').style,
        'CSS Custom Properties': window.CSS && CSS.supports('color', 'var(--test)'),
        'Canvas': !!document.createElement('canvas').getContext,
        'Local Storage': 'localStorage' in window,
        'Intersection Observer': 'IntersectionObserver' in window
    };

    const unsupported = Object.entries(features)
        .filter(([name, supported]) => !supported)
        .map(([name]) => name);

    if (unsupported.length > 0) {
        console.warn('Unsupported features:', unsupported);
        showErrorMessage(`您的浏览器不支持某些功能: ${unsupported.join(', ')}`);
    }
}

// 调试模式
function enableDebugMode() {
    if (window.location.search.includes('debug=true')) {
        document.body.classList.add('debug-mode');

        // 添加调试信息显示
        const debugPanel = document.createElement('div');
        debugPanel.id = 'debug-panel';
        debugPanel.style.cssText = `
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 10px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            z-index: 10000;
            max-width: 300px;
        `;
        document.body.appendChild(debugPanel);

        // 更新调试信息
        setInterval(() => {
            debugPanel.innerHTML = `
                <div>Current Page: ${currentPage}</div>
                <div>Total Points: ${totalPoints}</div>
                <div>Circle Points: ${circlePoints}</div>
                <div>Pi Estimate: ${totalPoints > 0 ? (4 * circlePoints / totalPoints).toFixed(6) : 0}</div>
                <div>Animation Running: ${isRunning}</div>
                <div>Theme: ${isDarkTheme ? 'Dark' : 'Light'}</div>
            `;
        }, 1000);
    }
}

// 测试功能
function runBasicTests() {
    console.log('🧪 Running basic functionality tests...');

    // 测试页面导航
    const testNavigation = () => {
        const pages = ['welcome', 'simulation', 'analysis'];
        let testsPassed = 0;

        pages.forEach(page => {
            const pageElement = document.getElementById(`${page}-page`);
            if (pageElement) {
                testsPassed++;
                console.log(`✅ ${page} page element found`);
            } else {
                console.log(`❌ ${page} page element not found`);
            }
        });

        console.log(`📊 Navigation test: ${testsPassed}/${pages.length} pages found`);
        return testsPassed === pages.length;
    };

    // 测试主题切换
    const testThemeToggle = () => {
        if (themeToggle) {
            console.log('✅ Theme toggle found');
            return true;
        } else {
            console.log('❌ Theme toggle not found');
            return false;
        }
    };

    // 运行测试
    const navigationTest = testNavigation();
    const themeTest = testThemeToggle();

    const allTestsPassed = navigationTest && themeTest;

    if (allTestsPassed) {
        console.log('🎉 All basic tests passed!');
    } else {
        console.log('⚠️ Some tests failed. Check the console for details.');
    }

    return allTestsPassed;
}

// 🚀 国奖级功能函数

// 成就系统检查
function checkAchievements(currentAccuracy, points) {
    achievementSystem.milestones.forEach(milestone => {
        if (currentAccuracy >= milestone && !achievementSystem.achieved.includes(milestone) && points > 100) {
            achievementSystem.achieved.push(milestone);
            
            // 触发成就效果
            triggerAchievement(milestone);
            
            // 触发粒子爆炸
            createParticleExplosion();
            
            // π值里程碑效果
            if (piValueOverlayElement) {
                piValueOverlayElement.classList.add('milestone');
                setTimeout(() => piValueOverlayElement.classList.remove('milestone'), 2000);
            }
        }
    });
}

// 触发成就弹窗
function triggerAchievement(milestone) {
    const popup = document.getElementById('achievementPopup');
    const text = popup.querySelector('.achievement-text');
    
    if (!popup || !text) return;
    
    const messages = {
        90: "精度突破90%！🎯",
        95: "卓越表现！达到95%！⭐",
        98: "大师级精度98%！👑", 
        99: "接近完美！99%精度！💎",
        99.9: "神级成就！99.9%！🚀"
    };
    
    text.textContent = messages[milestone] || `精度突破${milestone}%！`;
    popup.classList.add('show');
    
    // 3秒后隐藏
    setTimeout(() => {
        popup.classList.remove('show');
    }, 3000);
    
    // 播放成就音效（如果支持）
    playAchievementSound();
}

// 创建3D粒子爆炸效果
function createParticleExplosion() {
    if (!particleContainer) {
        particleContainer = document.getElementById('particle3DContainer');
    }
    
    if (!particleContainer || isParticleEffectActive) return;
    
    isParticleEffectActive = true;
    
    // 创建30个爆炸粒子
    for (let i = 0; i < 30; i++) {
        setTimeout(() => {
            createExplosionParticle();
        }, i * 50); // 交错创建
    }
    
    // 2秒后重置状态
    setTimeout(() => {
        isParticleEffectActive = false;
    }, 2000);
}

// 创建单个爆炸粒子
function createExplosionParticle() {
    const particle = document.createElement('div');
    particle.classList.add('particle-3d', 'particle-explosion');
    
    // 随机颜色
    const colors = ['#ffd700', '#ff6b35', '#4ecdc4', '#45b7d1', '#f9ca24'];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    particle.style.background = randomColor;
    particle.style.boxShadow = `0 0 10px ${randomColor}`;
    
    // 中心位置开始
    const centerX = particleContainer.offsetWidth / 2;
    const centerY = particleContainer.offsetHeight / 2;
    
    particle.style.left = centerX + 'px';
    particle.style.top = centerY + 'px';
    
    // 随机爆炸方向
    const angle = Math.random() * Math.PI * 2;
    const distance = 100 + Math.random() * 200;
    const dx = Math.cos(angle) * distance;
    const dy = Math.sin(angle) * distance;
    
    particle.style.setProperty('--dx', dx + 'px');
    particle.style.setProperty('--dy', dy + 'px');
    
    particleContainer.appendChild(particle);
    
    // 动画结束后移除
    setTimeout(() => {
        if (particle.parentNode) {
            particle.parentNode.removeChild(particle);
        }
    }, 2000);
}

// 播放成就音效（现代Web Audio API）
function playAchievementSound() {
    if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
        try {
            const AudioCtx = AudioContext || webkitAudioContext;
            const audioContext = new AudioCtx();
            
            // 创建简单的成就音效
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            oscillator.type = 'triangle';
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.exponentialRampToValueAtTime(1200, audioContext.currentTime + 0.3);
            
            gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.5);
        } catch (e) {
            console.log('Audio not supported');
        }
    }
}

// 🤖 AI智能助手核心功能

// 初始化AI助手
function initAIAssistant() {
    updateAIStatus('就绪', 'success');
    updateAIPrediction(95.0, 2500);
    updateAISuggestion("系统准备就绪，开始模拟以获取智能建议");
}

// 更新AI状态
function updateAIStatus(status, type = 'analyzing') {
    const statusElement = document.getElementById('aiStatus');
    const indicator = document.querySelector('.ai-indicator');
    
    if (statusElement) {
        statusElement.textContent = status;
    }
    
    if (indicator) {
        indicator.className = `ai-indicator ${type}`;
    }
}

// 更新AI建议
function updateAISuggestion(suggestion) {
    const element = document.getElementById('aiSuggestion');
    if (element) {
        element.textContent = suggestion;
        element.classList.add('updating');
        setTimeout(() => element.classList.remove('updating'), 500);
    }
}

// 更新AI预测
function updateAIPrediction(accuracy, points) {
    const accuracyElement = document.getElementById('predictedAccuracy');
    const pointsElement = document.getElementById('predictedPoints');
    
    if (accuracyElement) {
        accuracyElement.textContent = `${accuracy.toFixed(1)}%`;
    }
    if (pointsElement) {
        pointsElement.textContent = points.toLocaleString();
    }
}

// 运行AI分析
function runAIAnalysis(accuracy, points, error, currentSpeed) {
    if (aiAssistant.isAnalyzing) return;
    
    aiAssistant.isAnalyzing = true;
    updateAIStatus('分析中...', 'analyzing');
    
    // 模拟AI分析延迟
    setTimeout(() => {
        // 🧠 智能建议算法
        let suggestion = generateSmartSuggestion(accuracy, points, error, currentSpeed);
        let nextMilestone = predictNextMilestone(accuracy, points);
        
        updateAISuggestion(suggestion);
        updateAIPrediction(nextMilestone.accuracy, nextMilestone.points);
        updateAIStatus('分析完成', 'success');
        
        aiAssistant.isAnalyzing = false;
    }, 1500);
}

// 智能建议生成算法
function generateSmartSuggestion(accuracy, points, error, currentSpeed) {
    const suggestions = [];
    
    // 基于精度的建议
    if (accuracy < 80) {
        suggestions.push("精度较低，建议增加迭代点数至100以提升收敛速度");
    } else if (accuracy < 95) {
        suggestions.push("精度良好，可尝试增加迭代点数至1000获得更高精度");
    } else if (accuracy < 99) {
        suggestions.push("优秀精度！继续保持当前设置，即将突破99%");
    } else {
        suggestions.push("卓越表现！已达到极高精度，可尝试新的挑战");
    }
    
    // 基于速度的建议
    if (currentSpeed < 20) {
        suggestions.push("速度较慢，建议调整至30-50获得更好体验");
    } else if (currentSpeed > 80) {
        suggestions.push("速度过快可能影响精度观察，建议适当降低");
    }
    
    // 基于点数的建议
    if (points > 10000 && accuracy < 98) {
        suggestions.push("大量采样但精度未显著提升，建议重置并优化参数");
    }
    
    return suggestions[Math.floor(Math.random() * suggestions.length)] || "继续保持优秀表现！";
}

// 预测下个里程碑
function predictNextMilestone(currentAccuracy, currentPoints) {
    const milestones = [90, 95, 98, 99, 99.5, 99.9];
    const nextTarget = milestones.find(m => m > currentAccuracy) || 99.9;
    
    // 基于当前收敛速度预测所需点数
    const convergenceRate = Math.max(0.001, (currentAccuracy - 50) / currentPoints);
    const pointsNeeded = Math.ceil((nextTarget - currentAccuracy) / convergenceRate);
    
    return {
        accuracy: nextTarget,
        points: Math.min(pointsNeeded, 50000) // 限制最大预测值
    };
}

// 应用AI建议
function applyAIRecommendations() {
    const btn = document.getElementById('applyAITips');
    if (!btn) return;
    
    // 按钮动画效果
    btn.classList.add('applying');
    btn.innerHTML = '<i class="ri-loader-4-line"></i> 应用中...';
    
    setTimeout(() => {
        // 🎯 自动优化参数
        optimizeParameters();
        
        btn.classList.remove('applying');
        btn.innerHTML = '<i class="ri-magic-line"></i> 应用AI建议';
        
        // 显示应用成功提示
        showAIActionFeedback('AI建议已应用！参数已自动优化 ✨');
    }, 2000);
}

// 参数自动优化
function optimizeParameters() {
    const currentAccuracy = parseFloat(accuracyValue?.textContent || '0');
    
    if (currentAccuracy < 90) {
        // 低精度：增加迭代点数
        document.getElementById('points100')?.click();
        speedRange.value = 30;
        updateSpeed();
    } else if (currentAccuracy < 98) {
        // 中精度：平衡速度和点数
        document.getElementById('points100')?.click();
        speedRange.value = 50;
        updateSpeed();
    } else {
        // 高精度：追求极致精度
        document.getElementById('points1000')?.click();
        speedRange.value = 20;
        updateSpeed();
    }
}

// AI操作反馈
function showAIActionFeedback(message) {
    const feedback = document.createElement('div');
    feedback.className = 'ai-feedback';
    feedback.innerHTML = `
        <div class="ai-feedback-content">
            <i class="ri-ai-generate"></i>
            <span>${message}</span>
        </div>
    `;
    feedback.style.cssText = `
        position: fixed;
        top: 80px;
        right: 20px;
        background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
        color: white;
        padding: 12px 20px;
        border-radius: 25px;
        box-shadow: 0 8px 25px rgba(var(--primary-color-rgb), 0.3);
        z-index: 10000;
        animation: slideInRight 0.5s ease, slideOutRight 0.5s ease 3s forwards;
    `;
    
    document.body.appendChild(feedback);
    
    setTimeout(() => {
        if (feedback.parentNode) {
            feedback.parentNode.removeChild(feedback);
        }
    }, 3500);
}

// 🚀 社交分享功能

// 初始化社交分享
function setupSocialSharing() {
    const shareBtn = document.getElementById('shareResultBtn');
    const saveBtn = document.getElementById('saveImageBtn');
    const modal = document.getElementById('shareModal');
    const closeBtn = document.getElementById('shareCloseBtn');

    if (shareBtn) shareBtn.addEventListener('click', openShareModal);
    if (saveBtn) saveBtn.addEventListener('click', saveScreenshot);
    if (closeBtn) closeBtn.addEventListener('click', closeShareModal);
    if (modal) modal.addEventListener('click', (e) => {
        if (e.target === modal) closeShareModal();
    });

    // 社交平台分享按钮
    const weiboBtn = document.getElementById('shareWeibo');
    const wechatBtn = document.getElementById('shareWechat');
    const copyBtn = document.getElementById('shareCopy');
    const downloadBtn = document.getElementById('shareDownload');

    if (weiboBtn) weiboBtn.addEventListener('click', shareToWeibo);
    if (wechatBtn) wechatBtn.addEventListener('click', generateWeChatQR);
    if (copyBtn) copyBtn.addEventListener('click', copyShareText);
    if (downloadBtn) downloadBtn.addEventListener('click', downloadAchievementImage);
}

// 打开分享弹窗
function openShareModal() {
    const modal = document.getElementById('shareModal');
    if (!modal) return;

    // 更新分享数据
    updateShareData();
    
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';

    // 生成分享文本
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    
    const achievementText = document.getElementById('shareAchievementText');
    if (achievementText) {
        if (accuracy >= 99) {
            achievementText.textContent = `🚀 我在蒙特卡洛π值估算中达到了${accuracy}%的神级精度！`;
        } else if (accuracy >= 95) {
            achievementText.textContent = `⭐ 我在蒙特卡洛π值估算中达到了${accuracy}%的卓越精度！`;
        } else {
            achievementText.textContent = `🎯 我在蒙特卡洛π值估算中达到了${accuracy}%的精度！`;
        }
    }
}

// 关闭分享弹窗
function closeShareModal() {
    const modal = document.getElementById('shareModal');
    if (!modal) return;

    modal.classList.remove('active');
    document.body.style.overflow = 'auto';

    // 隐藏二维码
    const qrContainer = document.getElementById('qrContainer');
    if (qrContainer) qrContainer.classList.remove('active');
}

// 更新分享数据
function updateShareData() {
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    const error = errorElement?.textContent || '0';

    // 更新分享统计数据
    const shareStatPi = document.getElementById('shareStatPi');
    const shareStatAccuracy = document.getElementById('shareStatAccuracy');
    const shareStatPoints = document.getElementById('shareStatPoints');
    const shareStatError = document.getElementById('shareStatError');

    if (shareStatPi) shareStatPi.textContent = pi;
    if (shareStatAccuracy) shareStatAccuracy.textContent = `${accuracy}%`;
    if (shareStatPoints) shareStatPoints.textContent = points;
    if (shareStatError) shareStatError.textContent = error;
}

// 生成微信二维码
function generateWeChatQR() {
    const qrContainer = document.getElementById('qrContainer');
    if (!qrContainer) return;

    // 准备分享数据
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    
    const shareUrl = window.location.href;
    const shareTitle = `🎯 蒙特卡洛π值估算成果：${accuracy}%精度！`;
    const shareDesc = `通过${points}次采样估算出π ≈ ${pi}`;

    // 使用实际的二维码生成服务
    const qrcodeDiv = document.getElementById('qrcode');
    if (qrcodeDiv) {
        // 清空之前的内容
        qrcodeDiv.innerHTML = '';
        
        // 创建二维码 - 使用在线API生成真实二维码
        const qrText = `${shareTitle}\n${shareDesc}\n\n查看详情：${shareUrl}`;
        const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrText)}`;
        
        const qrImg = document.createElement('img');
        qrImg.src = qrApiUrl;
        qrImg.style.cssText = `
            width: 200px;
            height: 200px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        `;
        qrImg.alt = '微信分享二维码';
        
        // 添加加载状态
        qrImg.onload = () => {
            // 添加说明文字
            const description = document.createElement('div');
            description.style.cssText = `
                margin-top: 12px;
                text-align: center;
                color: var(--text-secondary);
                font-size: 0.9rem;
                line-height: 1.4;
            `;
            description.innerHTML = `
                <strong>📱 扫码分享到微信</strong><br>
                <small>或长按保存二维码图片</small>
            `;
            
            qrcodeDiv.appendChild(qrImg);
            qrcodeDiv.appendChild(description);
        };
        
        // 加载失败时的处理
        qrImg.onerror = () => {
            qrcodeDiv.innerHTML = `
                <div style="
                    width: 200px; 
                    height: 200px; 
                    background: #f5f5f5; 
                    display: flex; 
                    align-items: center; 
                    justify-content: center; 
                    border-radius: 8px;
                    flex-direction: column;
                    color: #666;
                    text-align: center;
                ">
                    <i class="ri-qr-code-line" style="font-size: 3rem; margin-bottom: 8px;"></i>
                    <div>二维码生成失败</div>
                    <div style="font-size: 0.8rem; margin-top: 4px;">请使用复制链接功能</div>
                </div>
            `;
        };
    }

    qrContainer.classList.add('active');
    
    // 触觉反馈
    if (navigator.vibrate) {
        navigator.vibrate(50);
    }
    
    showShareFeedback('正在生成微信二维码...');
}

// 分享到微博
function shareToWeibo() {
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const text = encodeURIComponent(`🎯 我在蒙特卡洛方法估算π值中达到了${accuracy}%的精度！估算值：π ≈ ${pi} ✨ #数学 #蒙特卡洛 #π值估算`);
    const url = encodeURIComponent(window.location.href);
    window.open(`https://service.weibo.com/share/share.php?title=${text}&url=${url}`, '_blank');
}

// 复制分享文本
function copyShareText() {
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    const error = errorElement?.textContent || '0';
    
    const shareText = `🎯 我的蒙特卡洛π值估算成果

📊 精确度：${accuracy}%
🔢 π估算值：${pi}
🎲 采样点数：${points}
📈 误差率：${error}

🔗 在线体验：${window.location.href}

#数学 #蒙特卡洛 #π值估算 #数据可视化`;

    if (navigator.clipboard) {
        navigator.clipboard.writeText(shareText).then(() => {
            showShareFeedback('🎉 分享文本已复制到剪贴板！');
        }).catch(() => {
            fallbackCopyText(shareText);
        });
    } else {
        fallbackCopyText(shareText);
    }
}

// 下载成果图
function downloadAchievementImage() {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    // 高分辨率画布
    canvas.width = 1200;
    canvas.height = 800;
    
    // 获取当前数据
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    const error = errorElement?.textContent || '0';
    
    // 背景渐变
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
    gradient.addColorStop(0, isDarkTheme ? '#0f172a' : '#f8fafc');
    gradient.addColorStop(1, isDarkTheme ? '#1e293b' : '#e2e8f0');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 主标题
    ctx.fillStyle = isDarkTheme ? '#f1f5f9' : '#1e293b';
    ctx.font = 'bold 48px "Microsoft YaHei", sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('🎯 蒙特卡洛π值估算成果', canvas.width / 2, 120);
    
    // π值显示
    ctx.font = 'bold 72px "JetBrains Mono", monospace';
    ctx.fillStyle = '#6366f1';
    ctx.fillText(`π ≈ ${pi}`, canvas.width / 2, 240);
    
    // 精确度
    ctx.font = 'bold 42px "Microsoft YaHei", sans-serif';
    ctx.fillStyle = accuracy >= 99 ? '#10b981' : accuracy >= 95 ? '#f59e0b' : '#ef4444';
    ctx.fillText(`精确度：${accuracy}%`, canvas.width / 2, 320);
    
    // 详细数据
    ctx.font = '28px "Microsoft YaHei", sans-serif';
    ctx.fillStyle = isDarkTheme ? '#94a3b8' : '#64748b';
    ctx.fillText(`采样点数：${points} | 误差率：${error}`, canvas.width / 2, 380);
    
    // 装饰性π符号
    ctx.font = '200px serif';
    ctx.fillStyle = isDarkTheme ? 'rgba(99, 102, 241, 0.1)' : 'rgba(99, 102, 241, 0.05)';
    ctx.fillText('π', canvas.width - 200, canvas.height - 100);
    
    // 底部信息
    ctx.font = 'bold 24px "Microsoft YaHei", sans-serif';
    ctx.fillStyle = '#8b5cf6';
    ctx.fillText('蒙特卡洛方法 | Monte Carlo Method', canvas.width / 2, canvas.height - 80);
    
    ctx.font = '20px "Microsoft YaHei", sans-serif';
    ctx.fillStyle = isDarkTheme ? '#64748b' : '#94a3b8';
    ctx.fillText(`生成时间：${new Date().toLocaleString('zh-CN')}`, canvas.width / 2, canvas.height - 40);
    
    // 下载图片
    const link = document.createElement('a');
    link.download = `π值估算成果_${accuracy}%_${Date.now()}.png`;
    link.href = canvas.toDataURL('image/png', 1.0);
    link.click();
    
    showShareFeedback('🖼️ 成果图片已保存到本地！');
    
    // 触觉反馈
    if (navigator.vibrate) {
        navigator.vibrate([100, 50, 100]);
    }
}

// 备用复制方法
function fallbackCopyText(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        showShareFeedback('链接已复制到剪贴板！');
    } catch (err) {
        showShareFeedback('复制失败，请手动复制');
    }
    document.body.removeChild(textArea);
}

// 保存截图
function saveScreenshot() {
    // 创建Canvas合成截图
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    canvas.width = 800;
    canvas.height = 600;
    
    // 绘制背景
    ctx.fillStyle = isDarkTheme ? '#0B101A' : '#f8fafc';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制标题
    ctx.fillStyle = isDarkTheme ? '#d1d5db' : '#1e293b';
    ctx.font = 'bold 24px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('蒙特卡洛π值估算成果', canvas.width / 2, 50);
    
    // 绘制主要数据
    const accuracy = parseFloat(accuracyValue?.textContent || '0');
    const pi = piValueElement?.textContent || '0';
    const points = totalPointsElement?.textContent || '0';
    
    ctx.font = 'bold 36px sans-serif';
    ctx.fillStyle = '#6366f1';
    ctx.fillText(`π ≈ ${pi}`, canvas.width / 2, 150);
    
    ctx.font = 'bold 28px sans-serif';
    ctx.fillStyle = '#ec4899';
    ctx.fillText(`精确度: ${accuracy}%`, canvas.width / 2, 200);
    
    ctx.font = '20px sans-serif';
    ctx.fillStyle = isDarkTheme ? '#9ca3af' : '#64748b';
    ctx.fillText(`采样点数: ${points}`, canvas.width / 2, 250);
    
    // 绘制装饰元素
    ctx.fillStyle = '#10b981';
    ctx.font = 'bold 18px sans-serif';
    ctx.fillText('蒙特卡洛方法 | Monte Carlo Method', canvas.width / 2, canvas.height - 30);
    
    // 下载图片
    const link = document.createElement('a');
    link.download = `pi-estimation-${accuracy}%-${Date.now()}.png`;
    link.href = canvas.toDataURL();
    link.click();
    
    showShareFeedback('截图已保存！📸');
}

// 分享反馈提示
function showShareFeedback(message) {
    const feedback = document.createElement('div');
    feedback.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: var(--primary-gradient);
        color: white;
        padding: 15px 25px;
        border-radius: var(--border-radius);
        box-shadow: var(--shadow-lg);
        z-index: 10001;
        animation: fadeIn 0.3s ease, fadeOut 0.3s ease 2s forwards;
        font-weight: 600;
    `;
    feedback.textContent = message;
    document.body.appendChild(feedback);
    
    setTimeout(() => {
        if (feedback.parentNode) {
            feedback.parentNode.removeChild(feedback);
        }
    }, 2500);
}

// 🎮 真实排行榜和数据记录系统

// 数据存储管理
const DataManager = {
    // 获取用户数据
    getUserData() {
        const data = localStorage.getItem('piEstimationUserData');
        return data ? JSON.parse(data) : {
            totalSimulations: 0,
            bestAccuracy: 0,
            totalPoints: 0,
            totalTime: 0,
            level: 1,
            experience: 0,
            achievements: [],
            sessionHistory: [],
            personalBests: {
                highestAccuracy: { value: 0, date: null, points: 0 },
                fastestConvergence: { value: Infinity, date: null, points: 0 },
                mostPoints: { value: 0, date: null, accuracy: 0 }
            }
        };
    },

    // 保存用户数据
    saveUserData(data) {
        localStorage.setItem('piEstimationUserData', JSON.stringify(data));
    },

    // 记录一次模拟会话
    recordSession(sessionData) {
        const userData = this.getUserData();
        
        // 更新基本统计
        userData.totalSimulations++;
        userData.totalPoints += sessionData.points;
        userData.bestAccuracy = Math.max(userData.bestAccuracy, sessionData.accuracy);
        
        // 更新个人最佳记录
        if (sessionData.accuracy > userData.personalBests.highestAccuracy.value) {
            userData.personalBests.highestAccuracy = {
                value: sessionData.accuracy,
                date: new Date().toISOString(),
                points: sessionData.points
            };
        }
        
        if (sessionData.points > userData.personalBests.mostPoints.value) {
            userData.personalBests.mostPoints = {
                value: sessionData.points,
                date: new Date().toISOString(),
                accuracy: sessionData.accuracy
            };
        }
        
        // 记录会话历史（保留最近50次）
        userData.sessionHistory.unshift({
            accuracy: sessionData.accuracy,
            points: sessionData.points,
            piValue: sessionData.piValue,
            error: sessionData.error,
            date: new Date().toISOString(),
            duration: sessionData.duration || 0
        });
        
        if (userData.sessionHistory.length > 50) {
            userData.sessionHistory = userData.sessionHistory.slice(0, 50);
        }
        
        // 更新经验和等级
        const expGained = Math.floor(sessionData.accuracy) + Math.floor(sessionData.points / 1000);
        userData.experience += expGained;
        
        // 等级计算：每100经验升1级
        const newLevel = Math.floor(userData.experience / 100) + 1;
        if (newLevel > userData.level) {
            userData.level = newLevel;
            showLevelUpNotification(newLevel);
        }
        
        // 检查成就
        this.checkAchievements(userData, sessionData);
        
        this.saveUserData(userData);
        return userData;
    },

    // 检查成就解锁
    checkAchievements(userData, sessionData) {
        const achievements = [
            { id: 'precision-90', condition: () => sessionData.accuracy >= 90, name: 'π值入门', icon: '🥉' },
            { id: 'precision-95', condition: () => sessionData.accuracy >= 95, name: '精度专家', icon: '🥈' },
            { id: 'precision-99', condition: () => sessionData.accuracy >= 99, name: 'π值大师', icon: '🥇' },
            { id: 'precision-999', condition: () => sessionData.accuracy >= 99.9, name: '传奇精度', icon: '💎' },
            { id: 'points-1000', condition: () => userData.totalPoints >= 1000, name: '千点里程', icon: '🎯' },
            { id: 'points-10000', condition: () => userData.totalPoints >= 10000, name: '万点征程', icon: '🎲' },
            { id: 'points-100000', condition: () => userData.totalPoints >= 100000, name: '十万征途', icon: '⭐' },
            { id: 'simulations-10', condition: () => userData.totalSimulations >= 10, name: '坚持不懈', icon: '💪' },
            { id: 'simulations-50', condition: () => userData.totalSimulations >= 50, name: '持之以恒', icon: '🔥' }
        ];

        achievements.forEach(achievement => {
            if (!userData.achievements.includes(achievement.id) && achievement.condition()) {
                userData.achievements.push(achievement.id);
                showAchievementUnlock(achievement);
            }
        });
    },

    // 获取排行榜数据
    getLeaderboardData() {
        const userData = this.getUserData();
        const leaderboard = [];
        
        // 添加当前用户数据
        if (userData.bestAccuracy > 0) {
            leaderboard.push({
                name: '你',
                score: userData.bestAccuracy,
                points: userData.totalPoints,
                simulations: userData.totalSimulations,
                isCurrentUser: true,
                badge: this.getBadgeType(userData.bestAccuracy)
            });
        }
        
        // 添加一些基准数据（模拟其他用户）
        const benchmarkData = [
            { name: '数学达人', score: 99.2, points: 50000, simulations: 25 },
            { name: 'π探索者', score: 98.8, points: 35000, simulations: 18 },
            { name: '算法高手', score: 97.9, points: 28000, simulations: 15 },
            { name: '统计专家', score: 96.5, points: 22000, simulations: 12 },
            { name: '概率大师', score: 95.3, points: 18000, simulations: 10 }
        ];
        
        // 只有当用户有记录时才添加基准数据
        if (userData.totalSimulations > 0) {
            benchmarkData.forEach(data => {
                leaderboard.push({
                    ...data,
                    badge: this.getBadgeType(data.score),
                    isCurrentUser: false
                });
            });
        }
        
        // 按分数排序并返回前10名
        return leaderboard.sort((a, b) => b.score - a.score).slice(0, 10);
    },

    getBadgeType(accuracy) {
        if (accuracy >= 99) return 'gold';
        if (accuracy >= 95) return 'silver';
        if (accuracy >= 90) return 'bronze';
        return 'none';
    }
};

// 显示等级提升通知
function showLevelUpNotification(newLevel) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: linear-gradient(135deg, #ffd700, #ff6b35);
        color: white;
        padding: 25px 35px;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(255, 215, 0, 0.3);
        z-index: 10002;
        text-align: center;
        animation: levelUpPulse 2s ease-in-out;
        font-weight: bold;
    `;
    
    notification.innerHTML = `
        <div style="font-size: 2rem; margin-bottom: 8px;">🎉</div>
        <div style="font-size: 1.3rem; margin-bottom: 5px;">恭喜升级！</div>
        <div style="font-size: 1.1rem;">等级 ${newLevel}</div>
    `;
    
    document.body.appendChild(notification);
    
    // 触觉反馈
    if (navigator.vibrate) {
        navigator.vibrate([200, 100, 200, 100, 200]);
    }
    
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 显示成就解锁通知
function showAchievementUnlock(achievement) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #6366f1, #8b5cf6);
        color: white;
        padding: 20px 25px;
        border-radius: 12px;
        box-shadow: 0 8px 25px rgba(99, 102, 241, 0.3);
        z-index: 10003;
        min-width: 280px;
        animation: achievementSlideIn 0.5s ease-out;
    `;
    
    notification.innerHTML = `
        <div style="display: flex; align-items: center; gap: 12px;">
            <div style="font-size: 2rem;">${achievement.icon}</div>
            <div>
                <div style="font-weight: bold; font-size: 1.1rem;">成就解锁！</div>
                <div style="opacity: 0.9;">${achievement.name}</div>
            </div>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (notification.parentNode) {
            notification.style.animation = 'achievementSlideOut 0.3s ease-in forwards';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }
    }, 4000);
}

// 初始化排行榜
function initLeaderboard() {
    updateRealLeaderboard();
}

// 更新真实排行榜
function updateRealLeaderboard() {
    const leaderboardData = DataManager.getLeaderboardData();
    renderRealLeaderboard(leaderboardData);
}

// 渲染真实排行榜
function renderRealLeaderboard(data) {
    const leaderboard = document.getElementById('miniLeaderboard');
    if (!leaderboard) return;
    
    // 清空现有条目
    const existingEntries = leaderboard.querySelectorAll('.leaderboard-entry');
    existingEntries.forEach(entry => entry.remove());
    
    const h4 = leaderboard.querySelector('h4');
    
    if (data.length === 0) {
        // 如果没有数据，显示提示信息
        const placeholder = document.createElement('div');
        placeholder.className = 'leaderboard-placeholder';
        placeholder.innerHTML = `
            <div style="text-align: center; padding: 20px; color: var(--text-secondary);">
                <i class="ri-trophy-line" style="font-size: 2rem; opacity: 0.5;"></i>
                <p>开始模拟后显示排行榜</p>
            </div>
        `;
        
        if (h4.nextSibling) {
            leaderboard.insertBefore(placeholder, h4.nextSibling);
        } else {
            leaderboard.appendChild(placeholder);
        }
        return;
    }
    
    // 插入排行榜条目
    data.forEach((item, index) => {
        const entry = document.createElement('div');
        entry.className = `leaderboard-entry ${item.isCurrentUser ? 'current-user' : ''}`;
        entry.innerHTML = `
            <div class="leaderboard-rank">${index + 1}</div>
            <div class="leaderboard-name">${item.name}</div>
            <div class="leaderboard-score">${item.score.toFixed(1)}%</div>
        `;
        
        if (h4.nextSibling) {
            leaderboard.insertBefore(entry, h4.nextSibling);
        } else {
            leaderboard.appendChild(entry);
        }
    });
    
    // 更新徽章显示
    const userData = DataManager.getUserData();
    updateRealBadgeCollection(userData.bestAccuracy);
}

// 更新徽章集合（基于真实数据）
function updateRealBadgeCollection(bestAccuracy) {
    const badgeCollection = document.querySelector('.badge-collection');
    if (!badgeCollection) return;
    
    const badges = badgeCollection.querySelectorAll('.achievement-badge');
    badges.forEach(badge => {
        const tooltip = badge.getAttribute('data-tooltip');
        let isUnlocked = false;
        
        if (tooltip.includes('99%+') && bestAccuracy >= 99) {
            isUnlocked = true;
        } else if (tooltip.includes('95%+') && bestAccuracy >= 95) {
            isUnlocked = true;
        } else if (tooltip.includes('90%+') && bestAccuracy >= 90) {
            isUnlocked = true;
        }
        
        badge.style.opacity = isUnlocked ? '1' : '0.3';
        if (isUnlocked) {
            badge.style.filter = 'drop-shadow(0 0 8px rgba(255, 215, 0, 0.6))';
        } else {
            badge.style.filter = 'none';
        }
    });
}

// 记录模拟完成并更新数据
function recordSimulationCompletion() {
    const currentAccuracy = parseFloat(accuracyValue?.textContent || '0');
    const currentPoints = parseInt(totalPointsElement?.textContent || '0');
    const currentPi = piValueElement?.textContent || '0';
    const currentError = errorElement?.textContent || '0';
    
    if (currentAccuracy > 0 && currentPoints > 0) {
        const sessionData = {
            accuracy: currentAccuracy,
            points: currentPoints,
            piValue: currentPi,
            error: parseFloat(currentError.replace('%', '')) || 0,
            duration: Date.now() - simulationStartTime || 0
        };
        
        // 记录到数据管理器
        const updatedUserData = DataManager.recordSession(sessionData);
        
        // 更新排行榜显示
        updateRealLeaderboard();
        
        // 更新成就中心数据
        updateAchievementsPage(updatedUserData);
        
        return updatedUserData;
    }
    
    return null;
}

// 更新成就中心页面数据
function updateAchievementsPage(userData) {
    if (!userData) return;
    
    // 更新用户统计信息
    const userLevel = document.getElementById('userLevelBadge');
    const userTitle = document.getElementById('userTitle');
    const expFill = document.getElementById('expFill');
    const expText = document.getElementById('expText');
    const userSimulations = document.getElementById('userSimulations');
    const userBestAccuracy = document.getElementById('userBestAccuracy');
    const userTotalPoints = document.getElementById('userTotalPoints');
    const userPlayTime = document.getElementById('userPlayTime');
    
    if (userLevel) userLevel.textContent = userData.level;
    if (userTitle) {
        const titles = ['π值探索者', '数学学徒', '计算能手', '统计专家', 'π值大师'];
        const titleIndex = Math.min(userData.level - 1, titles.length - 1);
        userTitle.textContent = titles[titleIndex];
    }
    
    if (expFill && expText) {
        const expInCurrentLevel = userData.experience % 100;
        const expNeeded = 100;
        expFill.style.width = `${expInCurrentLevel}%`;
        expText.textContent = `${expInCurrentLevel} / ${expNeeded} 经验`;
    }
    
    if (userSimulations) userSimulations.textContent = userData.totalSimulations;
    if (userBestAccuracy) userBestAccuracy.textContent = `${userData.bestAccuracy.toFixed(1)}%`;
    if (userTotalPoints) userTotalPoints.textContent = userData.totalPoints.toLocaleString();
    if (userPlayTime) {
        const minutes = Math.floor(userData.totalTime / 60000) || 0;
        userPlayTime.textContent = `${minutes}分钟`;
    }
    
    // 更新成就网格
    updateAchievementsGrid(userData);
}

// 更新成就网格
function updateAchievementsGrid(userData) {
    const achievementsGrid = document.getElementById('achievementsGrid');
    if (!achievementsGrid) return;
    
    const allAchievements = [
        { id: 'precision-90', name: 'π值入门', desc: '达到90%精度', icon: '🥉', category: 'precision' },
        { id: 'precision-95', name: '精度专家', desc: '达到95%精度', icon: '🥈', category: 'precision' },
        { id: 'precision-99', name: 'π值大师', desc: '达到99%精度', icon: '🥇', category: 'precision' },
        { id: 'precision-999', name: '传奇精度', desc: '达到99.9%精度', icon: '💎', category: 'precision' },
        { id: 'points-1000', name: '千点里程', desc: '采样1000个点', icon: '🎯', category: 'persistence' },
        { id: 'points-10000', name: '万点征程', desc: '采样10,000个点', icon: '🎲', category: 'persistence' },
        { id: 'points-100000', name: '十万征途', desc: '采样100,000个点', icon: '⭐', category: 'persistence' },
        { id: 'simulations-10', name: '坚持不懈', desc: '完成10次模拟', icon: '💪', category: 'persistence' },
        { id: 'simulations-50', name: '持之以恒', desc: '完成50次模拟', icon: '🔥', category: 'persistence' }
    ];
    
    achievementsGrid.innerHTML = '';
    
    allAchievements.forEach(achievement => {
        const isUnlocked = userData.achievements.includes(achievement.id);
        const achievementDiv = document.createElement('div');
        achievementDiv.className = `achievement-item ${isUnlocked ? 'unlocked' : 'locked'}`;
        achievementDiv.setAttribute('data-category', achievement.category);
        
        achievementDiv.innerHTML = `
            <div class="achievement-icon">${achievement.icon}</div>
            <div class="achievement-info">
                <h4>${achievement.name}</h4>
                <p>${achievement.desc}</p>
                <div class="achievement-status">
                    ${isUnlocked ? '<span class="status-unlocked">✓ 已解锁</span>' : '<span class="status-locked">🔒 未解锁</span>'}
                </div>
            </div>
        `;
        
        achievementsGrid.appendChild(achievementDiv);
    });
}

// 更新徽章集合
function updateBadgeCollection(currentAccuracy) {
    const badgeCollection = document.querySelector('.badge-collection');
    if (!badgeCollection) return;
    
    const badges = badgeCollection.querySelectorAll('.achievement-badge');
    badges.forEach(badge => {
        const tooltip = badge.getAttribute('data-tooltip');
        if (tooltip.includes('99%+') && currentAccuracy >= 99) {
            badge.style.opacity = '1';
        } else if (tooltip.includes('95%+') && currentAccuracy >= 95) {
            badge.style.opacity = '1';
        } else if (tooltip.includes('90%+') && currentAccuracy >= 90) {
            badge.style.opacity = '1';
        } else {
            badge.style.opacity = '0.3';
        }
    });
}

// 📱 移动端手势控制功能

let touchState = {
    isTouch: false,
    startX: 0,
    startY: 0,
    lastX: 0,
    lastY: 0,
    startDistance: 0,
    isPinching: false,
    swipeThreshold: 50,
    longPressTimer: null,
    longPressDelay: 800
};

// 初始化移动端手势
function initMobileGestures() {
    if (!('ontouchstart' in window)) return; // 仅在触摸设备上启用

    const canvas = document.getElementById('simulationCanvas');
    if (!canvas) return;

    // 阻止默认触摸行为
    canvas.style.touchAction = 'none';

    // 单指触摸
    canvas.addEventListener('touchstart', handleTouchStart, { passive: false });
    canvas.addEventListener('touchmove', handleTouchMove, { passive: false });
    canvas.addEventListener('touchend', handleTouchEnd, { passive: false });

    // 添加移动端优化提示
    addMobileTips();
}

// 触摸开始
function handleTouchStart(e) {
    e.preventDefault();
    
    const touches = e.touches;
    touchState.isTouch = true;

    if (touches.length === 1) {
        // 单指操作
        const touch = touches[0];
        touchState.startX = touchState.lastX = touch.clientX;
        touchState.startY = touchState.lastY = touch.clientY;

        // 长按检测
        touchState.longPressTimer = setTimeout(() => {
            handleLongPress(touch);
        }, touchState.longPressDelay);

        // 触觉反馈
        if (navigator.vibrate) {
            navigator.vibrate(10);
        }
    } else if (touches.length === 2) {
        // 双指操作（缩放控制速度）
        clearTimeout(touchState.longPressTimer);
        touchState.isPinching = true;
        
        const touch1 = touches[0];
        const touch2 = touches[1];
        touchState.startDistance = getDistance(touch1, touch2);

        // 触觉反馈
        if (navigator.vibrate) {
            navigator.vibrate([50, 50, 50]);
        }
    }
}

// 触摸移动
function handleTouchMove(e) {
    e.preventDefault();
    
    const touches = e.touches;

    if (touches.length === 1 && !touchState.isPinching) {
        // 单指滑动
        const touch = touches[0];
        const deltaX = touch.clientX - touchState.lastX;
        const deltaY = touch.clientY - touchState.lastY;

        // 取消长按
        clearTimeout(touchState.longPressTimer);

        // 横向滑动控制速度
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            const speedChange = Math.sign(deltaX) * 2;
            adjustSpeed(speedChange);
        }

        touchState.lastX = touch.clientX;
        touchState.lastY = touch.clientY;
    } else if (touches.length === 2) {
        // 双指缩放控制点数
        const touch1 = touches[0];
        const touch2 = touches[1];
        const currentDistance = getDistance(touch1, touch2);
        
        if (touchState.startDistance > 0) {
            const scale = currentDistance / touchState.startDistance;
            
            if (scale > 1.1) {
                // 放大手势 - 增加点数
                adjustPointsPerIteration(1);
                touchState.startDistance = currentDistance;
            } else if (scale < 0.9) {
                // 缩小手势 - 减少点数
                adjustPointsPerIteration(-1);
                touchState.startDistance = currentDistance;
            }
        }
    }
}

// 触摸结束
function handleTouchEnd(e) {
    e.preventDefault();
    
    const changedTouches = e.changedTouches;
    clearTimeout(touchState.longPressTimer);

    if (e.touches.length === 0) {
        // 所有手指离开
        const deltaX = touchState.lastX - touchState.startX;
        const deltaY = touchState.lastY - touchState.startY;
        
        // 检测滑动手势
        if (Math.abs(deltaX) > touchState.swipeThreshold) {
            if (deltaX > 0) {
                handleSwipeRight();
            } else {
                handleSwipeLeft();
            }
        } else if (Math.abs(deltaY) > touchState.swipeThreshold) {
            if (deltaY < 0) {
                handleSwipeUp();
            } else {
                handleSwipeDown();
            }
        } else if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10) {
            // 点击
            handleTap();
        }

        touchState.isTouch = false;
        touchState.isPinching = false;
    }
}

// 长按处理
function handleLongPress(touch) {
    // 长按重置模拟
    resetSimulation();
    showGestureHint('长按重置 ✨');
    
    if (navigator.vibrate) {
        navigator.vibrate(100);
    }
}

// 点击处理
function handleTap() {
    // 点击开始/暂停
    toggleSimulation();
    showGestureHint(isRunning ? '开始模拟 ▶️' : '暂停模拟 ⏸️');
}

// 滑动手势处理
function handleSwipeLeft() {
    // 左滑减速
    adjustSpeed(-5);
    showGestureHint('减速 🐌');
}

function handleSwipeRight() {
    // 右滑加速
    adjustSpeed(5);
    showGestureHint('加速 🚀');
}

function handleSwipeUp() {
    // 上滑切换页面
    if (currentPage === 'simulation') {
        navigateToPage('analysis');
        showGestureHint('切换到分析页 📊');
    }
}

function handleSwipeDown() {
    // 下滑切换页面
    if (currentPage === 'analysis') {
        navigateToPage('simulation');
        showGestureHint('返回模拟页 🎯');
    }
}

// 辅助函数
function getDistance(touch1, touch2) {
    const dx = touch1.clientX - touch2.clientX;
    const dy = touch1.clientY - touch2.clientY;
    return Math.sqrt(dx * dx + dy * dy);
}

function adjustSpeed(change) {
    const speedRange = document.getElementById('speed');
    if (speedRange) {
        const newValue = Math.max(1, Math.min(100, speed + change));
        speedRange.value = newValue;
        speed = newValue;
        
        // 更新显示
        const speedValue = document.getElementById('speedValue');
        if (speedValue) {
            speedValue.textContent = speed;
            speedValue.classList.add('changing');
            setTimeout(() => speedValue.classList.remove('changing'), 300);
        }
    }
}

function adjustPointsPerIteration(direction) {
    const currentIndex = [1, 10, 100, 1000].indexOf(pointsPerIteration);
    let newIndex = currentIndex;
    
    if (direction > 0 && currentIndex < 3) {
        newIndex = currentIndex + 1;
    } else if (direction < 0 && currentIndex > 0) {
        newIndex = currentIndex - 1;
    }
    
    if (newIndex !== currentIndex) {
        pointsPerIteration = [1, 10, 100, 1000][newIndex];
        
        // 更新UI
        const buttons = document.querySelectorAll('[data-points]');
        buttons.forEach(btn => btn.classList.remove('active'));
        
        const activeBtn = document.querySelector(`[data-points="${pointsPerIteration}"]`);
        if (activeBtn) {
            activeBtn.classList.add('active');
        }
        
        showGestureHint(`点数: ${pointsPerIteration} 🎯`);
    }
}

// 显示手势提示
function showGestureHint(message) {
    const hint = document.createElement('div');
    hint.style.cssText = `
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 0.9rem;
        font-weight: 600;
        z-index: 1000;
        pointer-events: none;
        animation: fadeIn 0.3s ease, fadeOut 0.3s ease 1.5s forwards;
    `;
    hint.textContent = message;
    document.body.appendChild(hint);
    
    setTimeout(() => {
        if (hint.parentNode) {
            hint.parentNode.removeChild(hint);
        }
    }, 2000);
}

// 添加移动端使用提示
function addMobileTips() {
    const tips = document.createElement('div');
    tips.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: var(--glass-background);
        backdrop-filter: blur(10px);
        border: var(--glass-border);
        border-radius: var(--border-radius);
        padding: 10px;
        font-size: 0.8rem;
        color: var(--text-secondary);
        z-index: 1000;
        opacity: 0.8;
        transition: opacity 0.3s ease;
    `;
    tips.innerHTML = `
        <div style="font-weight: bold; margin-bottom: 5px;">📱 手势操作</div>
        <div>• 点击: 开始/暂停</div>
        <div>• 长按: 重置</div>
        <div>• 左右滑动: 调速</div>
        <div>• 上下滑动: 切换页面</div>
        <div>• 双指缩放: 调整点数</div>
    `;
    
    tips.addEventListener('click', () => {
        tips.style.opacity = tips.style.opacity === '0' ? '0.8' : '0';
    });
    
    document.body.appendChild(tips);
    
    // 3秒后自动淡出
    setTimeout(() => {
        tips.style.opacity = '0.3';
    }, 3000);
}

// 🎓 教学页面功能
let tutorialDemoRunning = false;
let tutorialAnimationId = null;

// 初始化教学演示
function initTutorialDemo() {
    const tutorialCanvas = document.getElementById('tutorialCanvas');
    if (!tutorialCanvas) return;

    const ctx = tutorialCanvas.getContext('2d');
    const startBtn = document.getElementById('startTutorialDemo');
    const pauseBtn = document.getElementById('pauseTutorialDemo');
    const resetBtn = document.getElementById('resetTutorialDemo');
    const speedRange = document.getElementById('tutorialSpeed');
    const speedValue = document.getElementById('tutorialSpeedValue');

    let tutorialPoints = [];
    let tutorialStats = { total: 0, inside: 0 };

    // 绘制教学演示
    function drawTutorialDemo() {
        ctx.clearRect(0, 0, tutorialCanvas.width, tutorialCanvas.height);
        
        // 绘制正方形
        ctx.strokeStyle = '#6366f1';
        ctx.lineWidth = 3;
        ctx.strokeRect(50, 50, 300, 300);
        
        // 绘制圆
        ctx.strokeStyle = '#ec4899';
        ctx.beginPath();
        ctx.arc(200, 200, 150, 0, Math.PI * 2);
        ctx.stroke();
        
        // 绘制点
        tutorialPoints.forEach(point => {
            ctx.fillStyle = point.inside ? '#ef4444' : '#3b82f6';
            ctx.beginPath();
            ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
            ctx.fill();
        });
    }

    // 演示控制
    if (startBtn) {
        startBtn.addEventListener('click', () => {
            tutorialDemoRunning = true;
            startTutorialAnimation();
        });
    }

    if (pauseBtn) {
        pauseBtn.addEventListener('click', () => {
            tutorialDemoRunning = false;
            if (tutorialAnimationId) {
                clearTimeout(tutorialAnimationId);
            }
        });
    }

    if (resetBtn) {
        resetBtn.addEventListener('click', () => {
            tutorialDemoRunning = false;
            if (tutorialAnimationId) {
                clearTimeout(tutorialAnimationId);
            }
            tutorialPoints = [];
            tutorialStats = { total: 0, inside: 0 };
            updateTutorialStats();
            drawTutorialDemo();
        });
    }

    if (speedRange && speedValue) {
        speedRange.addEventListener('input', () => {
            speedValue.textContent = speedRange.value;
        });
    }

    // 开始演示动画
    function startTutorialAnimation() {
        if (!tutorialDemoRunning) return;

        const batchSize = parseInt(document.getElementById('tutorialBatchSize')?.value || 1);
        const speed = parseInt(speedRange?.value || 10);

        for (let i = 0; i < batchSize; i++) {
            const x = 50 + Math.random() * 300;
            const y = 50 + Math.random() * 300;
            const distance = Math.sqrt((x - 200) ** 2 + (y - 200) ** 2);
            const inside = distance <= 150;

            tutorialPoints.push({ x, y, inside });
            tutorialStats.total++;
            if (inside) tutorialStats.inside++;
        }

        updateTutorialStats();
        drawTutorialDemo();

        const delay = Math.max(50, 1000 - speed * 20);
        tutorialAnimationId = setTimeout(startTutorialAnimation, delay);
    }

    // 更新统计数据
    function updateTutorialStats() {
        const totalEl = document.getElementById('demoTotal');
        const insideEl = document.getElementById('demoInside');
        const piEl = document.getElementById('demoPi');
        const errorEl = document.getElementById('demoError');

        if (totalEl) totalEl.textContent = tutorialStats.total;
        if (insideEl) insideEl.textContent = tutorialStats.inside;

        if (tutorialStats.total > 0) {
            const piEstimate = 4 * (tutorialStats.inside / tutorialStats.total);
            const error = Math.abs(Math.PI - piEstimate) / Math.PI * 100;

            if (piEl) piEl.textContent = piEstimate.toFixed(4);
            if (errorEl) errorEl.textContent = error.toFixed(1) + '%';
        }
    }

    // 初始绘制
    drawTutorialDemo();
    updateTutorialStats();
}

// 显示开发状态
function showDevelopmentStatus(featureName) {
    console.log(`${featureName} 功能正在开发中...`);
}

// 🔍 算法对比页面功能
function initAlgorithmComparison() {
    const startBtn = document.getElementById('startComparison');
    const canvas = document.getElementById('comparisonCanvas');
    
    if (startBtn) {
        startBtn.addEventListener('click', runAlgorithmComparison);
    }

    // 初始化图表
    if (canvas) {
        drawComparisonChart(canvas, []);
    }
}

// 运行算法对比
function runAlgorithmComparison() {
    const iterations = parseInt(document.getElementById('comparisonIterations')?.value || 10000);
    
    // 更新状态
    updateComparisonStatus('running', '运行中...');
    
    // 运行蒙特卡洛算法
    setTimeout(() => {
        const startTime = performance.now();
        const mcResult = runMonteCarloComparison(iterations);
        const endTime = performance.now();
        
        // 更新结果显示
        updateComparisonResults({
            algorithm: 'monte-carlo',
            piValue: mcResult.pi,
            accuracy: mcResult.accuracy,
            time: (endTime - startTime).toFixed(2),
            iterations: iterations
        });
        
        updateComparisonStatus('ready', '完成');
        
        // 绘制收敛图表
        drawComparisonChart(document.getElementById('comparisonCanvas'), mcResult.convergence);
    }, 100);
}

// 蒙特卡洛算法对比实现
function runMonteCarloComparison(iterations) {
    let insideCircle = 0;
    const convergence = [];
    
    for (let i = 1; i <= iterations; i++) {
        const x = Math.random() * 2 - 1;
        const y = Math.random() * 2 - 1;
        
        if (x * x + y * y <= 1) {
            insideCircle++;
        }
        
        if (i % Math.floor(iterations / 100) === 0 || i <= 100) {
            const piEstimate = 4 * insideCircle / i;
            convergence.push({
                iteration: i,
                pi: piEstimate,
                accuracy: (100 - Math.abs(Math.PI - piEstimate) / Math.PI * 100)
            });
        }
    }
    
    const finalPi = 4 * insideCircle / iterations;
    const finalAccuracy = 100 - Math.abs(Math.PI - finalPi) / Math.PI * 100;
    
    return {
        pi: finalPi.toFixed(6),
        accuracy: finalAccuracy.toFixed(2),
        convergence: convergence
    };
}

// 更新对比状态
function updateComparisonStatus(status, message) {
    const statusElements = document.querySelectorAll('.status.ready');
    statusElements.forEach(el => {
        el.className = `status ${status}`;
        el.textContent = message;
    });
}

// 更新对比结果
function updateComparisonResults(result) {
    const resultEl = document.getElementById('mcResult');
    const accuracyEl = document.getElementById('mcAccuracy');
    const timeEl = document.getElementById('mcTime');
    
    if (resultEl) resultEl.textContent = result.piValue;
    if (accuracyEl) accuracyEl.textContent = result.accuracy + '%';
    if (timeEl) timeEl.textContent = result.time + 'ms';
}

// 绘制对比图表
function drawComparisonChart(canvas, data) {
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    if (!data || data.length === 0) {
        ctx.fillStyle = '#94a3b8';
        ctx.font = '16px sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText('点击"开始对比"查看收敛过程', canvas.width / 2, canvas.height / 2);
        return;
    }
    
    // 绘制背景网格
    ctx.strokeStyle = 'rgba(148, 163, 184, 0.2)';
    ctx.lineWidth = 1;
    
    for (let i = 0; i <= 10; i++) {
        const y = (canvas.height - 40) * i / 10 + 20;
        ctx.beginPath();
        ctx.moveTo(40, y);
        ctx.lineTo(canvas.width - 20, y);
        ctx.stroke();
    }
    
    // 绘制收敛曲线
    ctx.strokeStyle = '#6366f1';
    ctx.lineWidth = 2;
    ctx.beginPath();
    
    data.forEach((point, index) => {
        const x = 40 + (canvas.width - 60) * index / (data.length - 1);
        const y = canvas.height - 20 - (canvas.height - 40) * (point.pi - 2) / 2;
        
        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });
    
    ctx.stroke();
    
    // 绘制π线
    ctx.strokeStyle = '#ef4444';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    const piY = canvas.height - 20 - (canvas.height - 40) * (Math.PI - 2) / 2;
    ctx.beginPath();
    ctx.moveTo(40, piY);
    ctx.lineTo(canvas.width - 20, piY);
    ctx.stroke();
    ctx.setLineDash([]);
    
    // 标签
    ctx.fillStyle = '#475569';
    ctx.font = '12px sans-serif';
    ctx.textAlign = 'left';
    ctx.fillText('π = 3.14159...', 45, piY - 5);
}

// 启动屏幕管理
function initLoader() {
    const loader = document.querySelector('.championship-loader');
    const progressFill = loader?.querySelector('.progress-fill-championship');
    const progressPercentage = loader?.querySelector('.progress-percentage');
    const stageItems = loader?.querySelectorAll('.stage-item');
    
    if (!loader) return;
    
    const stages = [
        { text: '初始化数学引擎', duration: 500, percentage: 15 },
        { text: '加载可视化组件', duration: 400, percentage: 35 },
        { text: '配置蒙特卡罗算法', duration: 600, percentage: 60 },
        { text: '准备用户界面', duration: 300, percentage: 85 },
        { text: '启动完成', duration: 200, percentage: 100 }
    ];
    
    let currentStage = 0;
    let currentProgress = 0;
    
    function updateProgress() {                                        
        const stage = stages[currentStage];
        const targetProgress = stage.percentage;
        
        // 更新进度条
        const progressInterval = setInterval(() => {
            if (currentProgress >= targetProgress) {
                clearInterval(progressInterval);
                
                // 标记当前阶段完成
                if (stageItems[currentStage]) {
                    stageItems[currentStage].classList.add('completed');
                    stageItems[currentStage].classList.remove('active');
                }
                
                currentStage++;
                
                if (currentStage < stages.length) {
                    // 激活下一个阶段
                    if (stageItems[currentStage]) {
                        stageItems[currentStage].classList.add('active');
                    }
                    setTimeout(updateProgress, 100);
                } else {
                    // 所有阶段完成，隐藏加载屏幕
                    setTimeout(() => {
                        loader.classList.add('hidden');
                        setTimeout(() => {
                            loader.style.display = 'none';
                        }, 500);
                    }, 300);
                }
                return;
            }
            
            currentProgress += Math.random() * 3 + 1;
            currentProgress = Math.min(currentProgress, targetProgress);
            
            if (progressFill) {
                progressFill.style.width = currentProgress + '%';
            }
            if (progressPercentage) {
                progressPercentage.textContent = Math.floor(currentProgress) + '%';
            }
        }, 50);
    }
    
    // 激活第一个阶段
    if (stageItems[0]) {
        stageItems[0].classList.add('active');
    }
    
    // 开始加载进度
    setTimeout(updateProgress, 300);
}

// 性能监控面板交互
function initPerformanceMonitor() {
    const monitorPanel = document.querySelector('.performance-monitor-panel');
    const monitorToggle = document.querySelector('.monitor-toggle');
    
    if (!monitorPanel || !monitorToggle) return;
    
    // 切换面板显示/隐藏
    monitorToggle.addEventListener('click', () => {
        monitorPanel.classList.toggle('open');
    });
    
    // 模拟实时数据更新
    function updateMetrics() {
        const metrics = {
            fps: Math.floor(Math.random() * 10) + 55,
            memory: Math.floor(Math.random() * 20) + 45,
            cpu: Math.floor(Math.random() * 15) + 20,
            gpu: Math.floor(Math.random() * 25) + 30
        };
        
        // 更新FPS
        const fpsValue = monitorPanel.querySelector('[data-metric="fps"] .metric-value');
        if (fpsValue) fpsValue.textContent = metrics.fps + ' FPS';
        
        // 更新内存使用
        const memoryValue = monitorPanel.querySelector('[data-metric="memory"] .metric-value');
        if (memoryValue) memoryValue.textContent = metrics.memory + ' MB';
        
        // 更新CPU使用率
        const cpuValue = monitorPanel.querySelector('[data-metric="cpu"] .metric-value');
        if (cpuValue) cpuValue.textContent = metrics.cpu + '%';
        
        // 更新GPU使用率
        const gpuValue = monitorPanel.querySelector('[data-metric="gpu"] .metric-value');
        if (gpuValue) gpuValue.textContent = metrics.gpu + '%';
        
        // 更新效率条
        const efficiencyBars = monitorPanel.querySelectorAll('.efficiency-fill');
        efficiencyBars.forEach((bar, index) => {
            const values = [metrics.fps / 60 * 100, metrics.memory / 100 * 100, metrics.cpu, metrics.gpu];
            if (values[index] !== undefined) {
                bar.style.width = Math.min(values[index], 100) + '%';
            }
        });
    }
    
    // 定期更新数据
    setInterval(updateMetrics, 1000);
    updateMetrics(); // 立即更新一次
}

// 3D模拟功能实现
let scene3D, camera3D, renderer3D;
let sphere3D, cube3D, points3D = [];
let animationId3D = null;
let isRunning3D = false;
let totalPoints3D = 0;
let insidePoints3D = 0;
let particleCount3D = 1000;
let animationSpeed3D = 1;
let pointSize3D = 1;
let showGrid3D = true;
let showAxes3D = true;
let enableRotation3D = false;
let currentVisualizationMode = 'default';

// 初始化3D场景
function init3D() {
    const container = document.getElementById('threejs-container');
    console.log('3D容器元素:', container);
    
    if (!container) {
        console.error('找不到threejs-container元素');
        return;
    }

    // 检查容器尺寸
    const containerRect = container.getBoundingClientRect();
    console.log('容器尺寸:', {
        width: containerRect.width,
        height: containerRect.height,
        clientWidth: container.clientWidth,
        clientHeight: container.clientHeight
    });

    // 如果容器没有尺寸，设置默认尺寸
    let width = container.clientWidth || 800;
    let height = container.clientHeight || 600;
    
    if (width === 0 || height === 0) {
        width = 800;
        height = 600;
        container.style.width = width + 'px';
        container.style.height = height + 'px';
        console.log('设置了默认容器尺寸:', width, 'x', height);
    }

    // 检查Three.js是否可用
    if (typeof THREE === 'undefined') {
        console.error('Three.js库未加载');
        return;
    }

    // 创建场景
    scene3D = new THREE.Scene();
    
    // 创建星空背景
    scene3D.background = new THREE.Color(0x0a0a0f); // 深空背景色
    
    // 添加星空粒子
    createStarField();

    // 创建相机
    const aspect = width / height;
    camera3D = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
    camera3D.position.set(5, 5, 5); // 适应更大立方体的视角
    camera3D.lookAt(0, 0, 0); // 看向中心

    // 创建渲染器
    renderer3D = new THREE.WebGLRenderer({ 
        antialias: true,
        alpha: true // 启用透明背景
    });
    renderer3D.setSize(width, height);
    renderer3D.setClearColor(0x1a1a2e, 1); // 设置背景色和透明度
    renderer3D.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // 设备像素比
    
    // 清空容器并添加渲染器
    container.innerHTML = '';
    container.appendChild(renderer3D.domElement);
    
    console.log('渲染器已创建并添加到容器:', {
        rendererSize: { width: renderer3D.domElement.width, height: renderer3D.domElement.height },
        canvasElement: renderer3D.domElement
    });

    // 创建美化的立方体框架（边长为3.2，中心在原点）
    console.log('创建立方体框架...');
    const cubeGeometry = new THREE.BoxGeometry(3.2, 3.2, 3.2);
    const cubeEdges = new THREE.EdgesGeometry(cubeGeometry);
    const cubeMaterial = new THREE.LineBasicMaterial({ 
        color: 0x6366f1,
        transparent: true,
        opacity: 0.8
    });
    const cubeLines = new THREE.LineSegments(cubeEdges, cubeMaterial);
    scene3D.add(cubeLines);
    cube3D = cubeLines;
    console.log('立方体框架已添加到场景');

    // 创建美化的球体（半径为1.6）
    console.log('创建球体...');
    const sphereGeometry = new THREE.SphereGeometry(1.6, 64, 32);
    const sphereMaterial = new THREE.MeshPhongMaterial({ 
        color: 0xec4899, 
        opacity: 0.15,
        transparent: true,
        shininess: 100,
        side: THREE.DoubleSide
    });
    const sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
    scene3D.add(sphereMesh);
    
    // 添加球体边框以增强效果
    const sphereWireframe = new THREE.WireframeGeometry(sphereGeometry);
    const sphereWireframeMaterial = new THREE.LineBasicMaterial({ 
        color: 0xf43f5e, 
        opacity: 0.3, 
        transparent: true 
    });
    const sphereLines = new THREE.LineSegments(sphereWireframe, sphereWireframeMaterial);
    scene3D.add(sphereLines);
    sphere3D = sphereLines;
    
    console.log('球体已添加到场景');


    // 创建坐标轴
    if (showAxes3D) {
        console.log('添加坐标轴...');
        const axesHelper = new THREE.AxesHelper(2); // 更大的坐标轴
        axesHelper.name = 'axes';
        scene3D.add(axesHelper);
        console.log('坐标轴已添加');
    }

    // 创建网格
    if (showGrid3D) {
        console.log('添加网格...');
        const gridHelper = new THREE.GridHelper(4, 20, 0x666666, 0x444444);
        gridHelper.position.y = -1;
        gridHelper.name = 'grid';
        scene3D.add(gridHelper);
        console.log('网格已添加');
    }

    // 添加更强的灯光
    console.log('添加灯光...');
    const ambientLight = new THREE.AmbientLight(0x404040, 0.6); // 更亮的环境光
    scene3D.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0); // 更亮的定向光
    directionalLight.position.set(5, 5, 5);
    directionalLight.castShadow = false; // 暂时关闭阴影
    scene3D.add(directionalLight);
    
    // 添加额外的点光源
    const pointLight = new THREE.PointLight(0xffffff, 0.5, 100);
    pointLight.position.set(0, 5, 0);
    scene3D.add(pointLight);
    console.log('所有灯光已添加');

    // 添加轨道控制器
    let controls3D = null;
    if (typeof THREE.OrbitControls !== 'undefined') {
        console.log('创建轨道控制器...');
        controls3D = new THREE.OrbitControls(camera3D, renderer3D.domElement);
        controls3D.enableDamping = true;
        controls3D.dampingFactor = 0.05;
        controls3D.enableZoom = true;
        controls3D.enableRotate = true;
        controls3D.enablePan = true;
        controls3D.target.set(0, 0, 0); // 设置控制器目标
        controls3D.update();
        console.log('轨道控制器已创建');
    } else {
        console.warn('THREE.OrbitControls不可用，使用基本相机控制');
    }

    // 记录场景统计
    console.log('3D场景初始化完成:', {
        场景对象数量: scene3D.children.length,
        相机位置: camera3D.position,
        渲染器尺寸: { width, height },
        控制器可用: !!controls3D
    });

    // 启动渲染循环
    animate3D();
    
    // 立即渲染一帧以确保显示
    renderer3D.render(scene3D, camera3D);
    console.log('首帧已渲染');
    
    // 添加测试功能
    window.test3D = function() {
        console.log('=== 3D场景测试 ===');
        console.log('场景对象:', scene3D.children.length);
        console.log('渲染器:', renderer3D);
        console.log('相机位置:', camera3D.position);
        console.log('容器:', container);
        console.log('画布元素:', renderer3D.domElement);
        console.log('画布样式:', {
            width: renderer3D.domElement.style.width,
            height: renderer3D.domElement.style.height,
            display: renderer3D.domElement.style.display
        });
        
        // 手动渲染一帧
        renderer3D.render(scene3D, camera3D);
        console.log('测试渲染完成');
    };
    
    console.log('测试函数已创建: test3D()');
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', () => {
        if (container && renderer3D && camera3D) {
            const newWidth = container.clientWidth || 800;
            const newHeight = container.clientHeight || 600;
            
            camera3D.aspect = newWidth / newHeight;
            camera3D.updateProjectionMatrix();
            
            renderer3D.setSize(newWidth, newHeight);
            console.log('3D渲染器尺寸已更新:', newWidth, 'x', newHeight);
        }
    });

    // 初始化可视化模式选择器
    initVisualizationModes();
}

// 初始化可视化模式选择器
function initVisualizationModes() {
    // 支持原版和紧凑版两种模式卡片
    const modeCards = document.querySelectorAll('.mode-card, .mode-card-compact');
    console.log('找到可视化模式卡片:', modeCards.length);
    
    modeCards.forEach((card, index) => {
        console.log(`模式卡片 ${index}:`, card.dataset.mode);
        card.addEventListener('click', (e) => {
            console.log('可视化模式被点击:', card.dataset.mode);
            
            // 移除所有活动状态（包括原版和紧凑版）
            document.querySelectorAll('.mode-card, .mode-card-compact').forEach(c => c.classList.remove('active'));
            
            // 添加当前卡片的活动状态
            card.classList.add('active');
            
            // 更新当前模式
            const newMode = card.dataset.mode;
            currentVisualizationMode = newMode;
            
            // 应用可视化模式
            applyVisualizationMode(newMode);
            
            // 添加点击反馈动画
            card.style.transform = 'scale(0.95)';
            setTimeout(() => {
                card.style.transform = 'scale(1)';
            }, 150);
            
            console.log('可视化模式已切换为:', newMode);
        });
    });
}

// 应用可视化模式
function applyVisualizationMode(mode) {
    console.log('应用可视化模式:', mode);
    
    if (!scene3D || !sphere3D || !cube3D) {
        console.warn('3D场景未初始化，无法应用可视化模式');
        return;
    }
    
    switch (mode) {
        case 'default':
            applyDefaultMode();
            break;
        case 'heatmap':
            applyHeatmapMode();
            break;
        case 'path':
            applyPathMode();
            break;
        case 'statistical':
            applyStatisticalMode();
            break;
        default:
            console.warn('未知的可视化模式:', mode);
    }
}

// 标准模式
function applyDefaultMode() {
    console.log('应用标准模式');
    
    // 重置球体和立方体材质
    sphere3D.material.color.setHex(0xec4899);
    sphere3D.material.opacity = 0.3;
    sphere3D.material.transparent = true;
    
    cube3D.material.color.setHex(0x4f46e5);
    cube3D.material.opacity = 1.0;
    
    // 显示基本元素
    sphere3D.visible = true;
    cube3D.visible = true;
    
    // 设置背景
    scene3D.background = new THREE.Color(0x1a1a2e);
}

// 热力图模式
function applyHeatmapMode() {
    console.log('应用热力图模式');
    
    // 更温暖的色调
    sphere3D.material.color.setHex(0xff6b35);
    sphere3D.material.opacity = 0.5;
    
    cube3D.material.color.setHex(0x0066cc);
    
    // 更暗的背景突出热力效果
    scene3D.background = new THREE.Color(0x0a0a0a);
}

// 轨迹模式
function applyPathMode() {
    console.log('应用轨迹模式');
    
    // 轨迹风格的材质
    sphere3D.material.color.setHex(0x00ff88);
    sphere3D.material.opacity = 0.6;
    
    cube3D.material.color.setHex(0x888888);
    
    scene3D.background = new THREE.Color(0x111122);
}

// 统计模式
function applyStatisticalMode() {
    console.log('应用统计模式');
    
    // 数据可视化风格
    sphere3D.material.color.setHex(0x9d4edd);
    sphere3D.material.opacity = 0.4;
    
    cube3D.material.color.setHex(0x06ffa5);
    
    scene3D.background = new THREE.Color(0x0d1b2a);
}

// 创建星空背景
function createStarField() {
    const starGeometry = new THREE.BufferGeometry();
    const starCount = 1000;
    const positions = new Float32Array(starCount * 3);
    
    for (let i = 0; i < starCount * 3; i += 3) {
        // 在球形空间中分布星星
        const radius = Math.random() * 50 + 20;
        const theta = Math.random() * Math.PI * 2;
        const phi = Math.random() * Math.PI;
        
        positions[i] = radius * Math.sin(phi) * Math.cos(theta);
        positions[i + 1] = radius * Math.sin(phi) * Math.sin(theta);
        positions[i + 2] = radius * Math.cos(phi);
    }
    
    starGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    
    const starMaterial = new THREE.PointsMaterial({
        color: 0xffffff,
        size: 0.5,
        transparent: true,
        opacity: 0.8,
        sizeAttenuation: false
    });
    
    const starField = new THREE.Points(starGeometry, starMaterial);
    starField.name = 'starField';
    scene3D.add(starField);
    
    console.log('星空背景已创建');
}

// 3D动画循环
function animate3D() {
    if (!renderer3D || !scene3D || !camera3D) {
        console.warn('3D组件未初始化，跳过渲染');
        return;
    }
    
    requestAnimationFrame(animate3D);
    
    // 自动旋转
    if (enableRotation3D && cube3D && sphere3D) {
        cube3D.rotation.y += 0.005;
        sphere3D.rotation.y += 0.005;
    }
    
    // 星空轻微旋转
    const starField = scene3D.getObjectByName('starField');
    if (starField) {
        starField.rotation.y += 0.0005;
        starField.rotation.x += 0.0002;
    }
    
    // 更新控制器（如果存在）
    const controls = renderer3D.domElement.parentElement?.controls;
    if (controls && controls.update) {
        controls.update();
    }
    
    // 渲染场景
    renderer3D.render(scene3D, camera3D);
}

// 生成3D随机点
function generate3DPoints() {
    console.log('generate3DPoints called', { isRunning3D, scene3D: !!scene3D });
    
    if (!isRunning3D || !scene3D) {
        console.log('3D模拟未运行或场景未初始化');
        return;
    }

    const batchSize = Math.min(particleCount3D - totalPoints3D, Math.floor(animationSpeed3D * 10));
    console.log(`生成${batchSize}个3D点，当前总数: ${totalPoints3D}`);

    for (let i = 0; i < batchSize; i++) {
        // 在立方体内生成随机点 [-1.6, 1.6]
        const x = (Math.random() - 0.5) * 3.2;
        const y = (Math.random() - 0.5) * 3.2;
        const z = (Math.random() - 0.5) * 3.2;

        // 计算点到原点的距离
        const distance = Math.sqrt(x * x + y * y + z * z);
        const isInside = distance <= 1.6;

        if (isInside) {
            insidePoints3D++;
        }
        totalPoints3D++;

        // 创建美化的点几何体
        const pointSize = Math.max(0.015, pointSize3D * 0.015);
        const pointGeometry = new THREE.SphereGeometry(pointSize, 8, 6);
        
        // 使用发光材质
        const pointMaterial = new THREE.MeshPhongMaterial({
            color: isInside ? 0x00ff87 : 0xff4757,
            emissive: isInside ? 0x003320 : 0x331111,
            shininess: 100,
            transparent: true,
            opacity: 0.9
        });
        
        const point = new THREE.Mesh(pointGeometry, pointMaterial);
        point.position.set(x, y, z);
        
        // 添加随机的微小旋转和缩放变化
        point.rotation.set(
            Math.random() * Math.PI * 2,
            Math.random() * Math.PI * 2,
            Math.random() * Math.PI * 2
        );
        point.scale.setScalar(0.8 + Math.random() * 0.4); // 0.8-1.2 的随机缩放

        scene3D.add(point);
        points3D.push(point);

        // 限制场景中的点数以保持性能
        if (points3D.length > 3000) {
            const oldPoint = points3D.shift();
            scene3D.remove(oldPoint);
            oldPoint.geometry.dispose();
            oldPoint.material.dispose();
        }
    }

    // 更新统计信息
    update3DStats();

    if (totalPoints3D < particleCount3D) {
        setTimeout(generate3DPoints, Math.max(16, 1000 / (animationSpeed3D * 60))); // 最少16ms间隔
    } else {
        console.log('3D模拟完成');
        isRunning3D = false;
        updateControlButtons3D();
    }
}

// 更新3D统计信息
function update3DStats() {
    const piEstimate = totalPoints3D > 0 ? 6 * (insidePoints3D / totalPoints3D) : 0;
    const accuracy = totalPoints3D > 0 ? Math.max(0, 100 - Math.abs(piEstimate - Math.PI) / Math.PI * 100) : 0;
    
    // 更新显示元素
    const totalElement = document.getElementById('totalPoints3D');
    const insideElement = document.getElementById('insidePoints3D');
    const piElement = document.getElementById('piValue3D');
    const accuracyElement = document.getElementById('accuracy3D');
    const fpsElement = document.getElementById('fpsCounter');
    
    if (totalElement) totalElement.textContent = totalPoints3D.toLocaleString();
    if (insideElement) insideElement.textContent = insidePoints3D.toLocaleString();
    if (piElement) piElement.textContent = piEstimate.toFixed(4);
    if (accuracyElement) accuracyElement.textContent = accuracy.toFixed(1) + '%';
    if (fpsElement) fpsElement.textContent = '60'; // 模拟FPS显示
}

// 更新3D控制按钮状态
function updateControlButtons3D() {
    const startBtn = document.getElementById('start3DSimulation');
    const pauseBtn = document.getElementById('pause3DSimulation');
    
    if (startBtn && pauseBtn) {
        if (isRunning3D) {
            startBtn.disabled = true;
            pauseBtn.disabled = false;
            startBtn.innerHTML = '<i class="ri-play-circle-line"></i>运行中...';
        } else {
            startBtn.disabled = false;
            pauseBtn.disabled = true;
            startBtn.innerHTML = '<i class="ri-play-circle-line"></i>启动3D模拟';
        }
    }
}

// 重置3D模拟
function reset3DSimulation() {
    isRunning3D = false;
    totalPoints3D = 0;
    insidePoints3D = 0;
    
    // 移除所有点
    points3D.forEach(point => {
        scene3D.remove(point);
    });
    points3D = [];
    
    // 更新统计信息
    update3DStats();
    updateControlButtons3D();
}

// 互动实验室功能实现
let tutorialSimulation = {
    canvas: null,
    ctx: null,
    isRunning: false,
    totalPoints: 0,
    insidePoints: 0,
    points: [],
    animationId: null,
    speed: 25,
    batchSize: 10,
    particleSize: 2,
    displayMode: 'points',
    scale: 1,
    offsetX: 0,
    offsetY: 0,
    startTime: 0,
    lastUpdate: 0,
    fps: 0,
    frameCount: 0,
    lastFpsUpdate: 0,
    history: [],
    maxPoints: 10000
};

// 初始化互动实验室
function initTutorialLab() {
    const canvas = document.getElementById('tutorialCanvas');
    if (!canvas) {
        console.warn('找不到tutorialCanvas元素');
        return;
    }
    
    tutorialSimulation.canvas = canvas;
    tutorialSimulation.ctx = canvas.getContext('2d');
    
    // 设置高DPI支持
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    
    // 确保画布有有效尺寸
    if (rect.width === 0 || rect.height === 0) {
        // 设置默认尺寸
        canvas.width = 500 * dpr;
        canvas.height = 500 * dpr;
        canvas.style.width = '500px';
        canvas.style.height = '500px';
    } else {
        canvas.width = rect.width * dpr;
        canvas.height = rect.height * dpr;
        canvas.style.width = rect.width + 'px';
        canvas.style.height = rect.height + 'px';
    }
    
    tutorialSimulation.ctx.scale(dpr, dpr);
    
    // 添加鼠标事件监听
    canvas.addEventListener('mousemove', handleCanvasMouseMove);
    canvas.addEventListener('wheel', handleCanvasWheel, { passive: false });
    canvas.addEventListener('click', handleCanvasClick);
    
    // 初始化控制事件
    initTutorialControls();
    
    // 初始化画布
    drawTutorialCanvas();
    
    console.log('互动实验室初始化完成', {
        canvasSize: { width: canvas.width, height: canvas.height },
        styleSize: { width: canvas.style.width, height: canvas.style.height }
    });
    
    // 运行完整测试
    setTimeout(() => {
        testTutorialLab();
    }, 500);
}

// 绘制实验画布
function drawTutorialCanvas() {
    const ctx = tutorialSimulation.ctx;
    const canvas = tutorialSimulation.canvas;
    if (!ctx || !canvas) return;
    
    const width = canvas.width / (window.devicePixelRatio || 1);
    const height = canvas.height / (window.devicePixelRatio || 1);
    
    // 确保尺寸有效
    if (width <= 0 || height <= 0) return;
    
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 设置背景
    ctx.fillStyle = '#1a1a2e';
    ctx.fillRect(0, 0, width, height);
    
    // 计算中心和半径，确保半径为正数
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.max(10, Math.min(width, height) / 2 - 20);
    
    // 应用缩放和偏移
    ctx.save();
    ctx.translate(centerX + tutorialSimulation.offsetX, centerY + tutorialSimulation.offsetY);
    ctx.scale(tutorialSimulation.scale, tutorialSimulation.scale);
    
    // 绘制网格（可选）
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.lineWidth = 1;
    const gridSize = 20;
    for (let x = -radius; x <= radius; x += gridSize) {
        ctx.beginPath();
        ctx.moveTo(x, -radius);
        ctx.lineTo(x, radius);
        ctx.stroke();
    }
    for (let y = -radius; y <= radius; y += gridSize) {
        ctx.beginPath();
        ctx.moveTo(-radius, y);
        ctx.lineTo(radius, y);
        ctx.stroke();
    }
    
    // 绘制正方形边界
    ctx.strokeStyle = '#4f46e5';
    ctx.lineWidth = 3;
    ctx.strokeRect(-radius, -radius, radius * 2, radius * 2);
    
    // 绘制圆形边界
    ctx.strokeStyle = '#ec4899';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI * 2);
    ctx.stroke();
    
    // 绘制坐标轴
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.lineWidth = 1;
    // X轴
    ctx.beginPath();
    ctx.moveTo(-radius, 0);
    ctx.lineTo(radius, 0);
    ctx.stroke();
    // Y轴
    ctx.beginPath();
    ctx.moveTo(0, -radius);
    ctx.lineTo(0, radius);
    ctx.stroke();
    
    // 绘制点
    tutorialSimulation.points.forEach(point => {
        ctx.fillStyle = point.isInside ? '#10b981' : '#ef4444';
        ctx.beginPath();
        ctx.arc(point.x * radius, point.y * radius, tutorialSimulation.particleSize, 0, Math.PI * 2);
        ctx.fill();
    });
    
    ctx.restore();
    
    // 绘制坐标标签
    ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
    ctx.font = '12px Arial';
    ctx.fillText('(-1,-1)', 10, height - 10);
    ctx.fillText('(1,1)', width - 50, 20);
    ctx.fillText('(0,0)', centerX - 10, centerY + 15);
}

// 运行蒙特卡洛模拟
function runTutorialSimulation() {
    if (!tutorialSimulation.isRunning) {
        console.log('模拟已停止，退出运行循环');
        return;
    }
    
    const now = Date.now();
    const deltaTime = now - tutorialSimulation.lastUpdate;
    
    // 控制生成速度（降低最小间隔以确保可见）
    const minInterval = Math.max(10, 1000 / tutorialSimulation.speed);
    
    if (deltaTime >= minInterval) {
        // 生成一批点
        let pointsGenerated = 0;
        for (let i = 0; i < tutorialSimulation.batchSize && tutorialSimulation.totalPoints < tutorialSimulation.maxPoints; i++) {
            const x = (Math.random() - 0.5) * 2; // [-1, 1]
            const y = (Math.random() - 0.5) * 2; // [-1, 1]
            const distance = Math.sqrt(x * x + y * y);
            const isInside = distance <= 1;
            
            const point = { x, y, isInside };
            tutorialSimulation.points.push(point);
            tutorialSimulation.totalPoints++;
            pointsGenerated++;
            
            if (isInside) {
                tutorialSimulation.insidePoints++;
            }
            
            // 限制点数以避免性能问题
            if (tutorialSimulation.points.length > 5000) {
                tutorialSimulation.points.shift();
            }
        }
        
        console.log(`生成了 ${pointsGenerated} 个点，总计: ${tutorialSimulation.totalPoints}`);
        
        tutorialSimulation.lastUpdate = now;
        updateTutorialStats();
        drawTutorialCanvas();
    }
    
    // 更新FPS
    tutorialSimulation.frameCount++;
    if (now - tutorialSimulation.lastFpsUpdate >= 1000) {
        tutorialSimulation.fps = Math.round(tutorialSimulation.frameCount * 1000 / (now - tutorialSimulation.lastFpsUpdate));
        tutorialSimulation.frameCount = 0;
        tutorialSimulation.lastFpsUpdate = now;
        console.log('FPS:', tutorialSimulation.fps);
    }
    
    // 继续动画循环
    if (tutorialSimulation.isRunning) {
        tutorialSimulation.animationId = requestAnimationFrame(runTutorialSimulation);
    }
    
    // 检查是否完成
    if (tutorialSimulation.totalPoints >= tutorialSimulation.maxPoints) {
        console.log('达到最大点数，停止模拟');
        stopTutorialSimulation();
    }
}

// 更新统计信息
function updateTutorialStats() {
    const piEstimate = tutorialSimulation.totalPoints > 0 ? 
        4 * (tutorialSimulation.insidePoints / tutorialSimulation.totalPoints) : 0;
    const accuracy = tutorialSimulation.totalPoints > 0 ? 
        Math.max(0, 100 - Math.abs(piEstimate - Math.PI) / Math.PI * 100) : 0;
    const error = Math.abs(piEstimate - Math.PI) / Math.PI * 100;
    
    // 更新显示元素
    const elements = {
        demoTotal: tutorialSimulation.totalPoints.toLocaleString(),
        demoInside: tutorialSimulation.insidePoints.toLocaleString(),
        demoPi: piEstimate.toFixed(4),
        demoError: error.toFixed(2) + '%',
        totalTrend: `+${Math.round(tutorialSimulation.batchSize * tutorialSimulation.speed / 10)}/s`,
        insideTrend: (tutorialSimulation.insidePoints / tutorialSimulation.totalPoints * 100).toFixed(1) + '%',
        piTrend: `Δ: ${(piEstimate - Math.PI).toFixed(4)}`,
        errorTrend: `± ${error.toFixed(3)}`,
        avgFPS: tutorialSimulation.fps.toString(),
        runTime: formatTime(Date.now() - tutorialSimulation.startTime),
        memUsage: `${Math.round(tutorialSimulation.points.length * 24 / 1024)}KB`,
        convergenceAccuracy: accuracy.toFixed(1) + '%'
    };
    
    Object.entries(elements).forEach(([id, value]) => {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        } else {
            console.warn(`找不到元素: #${id}`);
        }
    });
    
    console.log('统计信息已更新:', {
        totalPoints: tutorialSimulation.totalPoints,
        insidePoints: tutorialSimulation.insidePoints,
        piEstimate: piEstimate.toFixed(4),
        error: error.toFixed(2) + '%'
    });
    
    // 更新鼠标坐标信息（如果有的话）
    updateMouseInfo();
    
    // 更新收敛进度条
    const progressBar = document.getElementById('convergenceProgress');
    if (progressBar) {
        const progress = Math.min(accuracy, 100);
        progressBar.style.width = progress + '%';
    }
    
    const convergenceLabel = document.getElementById('convergenceProgressLabel');
    if (convergenceLabel) {
        convergenceLabel.textContent = `${Math.round(accuracy)}% 达到稳定`;
    }
    
    // 更新AI分析
    updateAIAnalysis(piEstimate, accuracy, error);
}

// 更新AI分析
function updateAIAnalysis(piEstimate, accuracy, error) {
    const insights = document.getElementById('experimentInsights');
    if (!insights) return;
    
    let analysis = '';
    let iconClass = 'waiting';
    
    if (tutorialSimulation.totalPoints === 0) {
        analysis = '🎯 开始实验以获取AI实时分析';
        iconClass = 'waiting';
    } else if (tutorialSimulation.totalPoints < 100) {
        analysis = '🌱 采样初期，数据波动较大，建议继续增加样本';
        iconClass = 'info';
    } else if (accuracy < 90) {
        analysis = '⚡ 精度偏低，建议调整参数或增加采样点数量';
        iconClass = 'warning';
    } else if (accuracy < 95) {
        analysis = '📈 收敛良好，当前精度适中，可继续优化';
        iconClass = 'success';
    } else if (accuracy < 99) {
        analysis = '🎯 高精度达成！算法表现优异，接近理论最优';
        iconClass = 'excellent';
    } else {
        analysis = '🏆 完美收敛！达到极高精度，实验非常成功';
        iconClass = 'perfect';
    }
    
    insights.innerHTML = `
        <div class="insight-item ${iconClass}">
            <div class="insight-icon">🤖</div>
            <div class="insight-text">${analysis}</div>
        </div>
    `;
}

// 格式化时间
function formatTime(ms) {
    const seconds = Math.floor(ms / 1000) % 60;
    const minutes = Math.floor(ms / 60000) % 60;
    const hours = Math.floor(ms / 3600000);
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// 鼠标移动处理
function handleCanvasMouseMove(event) {
    const canvas = tutorialSimulation.canvas;
    const rect = canvas.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    
    // 转换为数学坐标 [-1, 1]
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.min(width, height) / 2 - 20;
    
    const mathX = (mouseX - centerX) / radius;
    const mathY = -(mouseY - centerY) / radius; // Y轴翻转
    const distance = Math.sqrt(mathX * mathX + mathY * mathY);
    
    // 更新显示
    updateMouseCoordinates(mathX, mathY, distance);
}

// 更新鼠标坐标显示
function updateMouseCoordinates(x, y, distance) {
    const mouseXElement = document.getElementById('mouseX');
    const mouseYElement = document.getElementById('mouseY');
    const mouseDistanceElement = document.getElementById('mouseDistance');
    
    if (mouseXElement) mouseXElement.textContent = x.toFixed(3);
    if (mouseYElement) mouseYElement.textContent = y.toFixed(3);
    if (mouseDistanceElement) mouseDistanceElement.textContent = distance.toFixed(3);
}

// 更新鼠标信息（占位符函数）
function updateMouseInfo() {
    // 这个函数用于更新鼠标相关的信息
    // 在实际的鼠标移动事件中调用 updateMouseCoordinates
}

// 测试互动实验室功能
function testTutorialLab() {
    console.log('=== 互动实验室测试开始 ===');
    
    // 测试DOM元素
    const elements = {
        canvas: document.getElementById('tutorialCanvas'),
        startBtn: document.getElementById('startAdvancedDemo'),
        resetBtn: document.getElementById('resetAdvancedDemo'),
        saveBtn: document.getElementById('saveExperiment'),
        speedSlider: document.getElementById('tutorialSpeed'),
        batchSelect: document.getElementById('tutorialBatchSize'),
        modeBtns: document.querySelectorAll('.mode-btn')
    };
    
    console.log('DOM元素检测结果:');
    Object.entries(elements).forEach(([name, element]) => {
        if (name === 'modeBtns') {
            console.log(`- ${name}: ${element.length} 个按钮`);
            element.forEach((btn, i) => {
                console.log(`  按钮${i}: ${btn.textContent.trim()}, mode: ${btn.dataset.mode}`);
            });
        } else {
            console.log(`- ${name}: ${element ? '✓' : '✗'}`);
        }
    });
    
    // 测试tutorialSimulation对象状态
    console.log('tutorialSimulation状态:');
    console.log('- canvas:', !!tutorialSimulation.canvas);
    console.log('- ctx:', !!tutorialSimulation.ctx);
    console.log('- isRunning:', tutorialSimulation.isRunning);
    console.log('- totalPoints:', tutorialSimulation.totalPoints);
    console.log('- speed:', tutorialSimulation.speed);
    console.log('- batchSize:', tutorialSimulation.batchSize);
    
    // 测试画布
    if (tutorialSimulation.canvas && tutorialSimulation.ctx) {
        console.log('画布信息:');
        console.log('- 尺寸:', tutorialSimulation.canvas.width, 'x', tutorialSimulation.canvas.height);
        console.log('- 样式尺寸:', tutorialSimulation.canvas.style.width, tutorialSimulation.canvas.style.height);
        
        // 尝试在画布上绘制一个测试点
        try {
            const ctx = tutorialSimulation.ctx;
            ctx.save();
            ctx.fillStyle = '#00ff00';
            ctx.beginPath();
            ctx.arc(250, 250, 5, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
            console.log('✓ 测试绘制成功');
        } catch (error) {
            console.error('✗ 测试绘制失败:', error);
        }
    }
    
    console.log('=== 互动实验室测试结束 ===');
    return elements;
}

// 鼠标滚轮缩放处理
function handleCanvasWheel(event) {
    event.preventDefault();
    
    const delta = event.deltaY > 0 ? 0.9 : 1.1;
    tutorialSimulation.scale = Math.max(0.1, Math.min(5, tutorialSimulation.scale * delta));
    
    drawTutorialCanvas();
}

// 鼠标点击处理（手动添加点）
function handleCanvasClick(event) {
    const canvas = tutorialSimulation.canvas;
    const rect = canvas.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    
    // 转换为数学坐标 [-1, 1]
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.min(width, height) / 2 - 20;
    
    const mathX = (mouseX - centerX) / radius;
    const mathY = -(mouseY - centerY) / radius; // Y轴翻转
    const distance = Math.sqrt(mathX * mathX + mathY * mathY);
    const isInside = distance <= 1;
    
    // 添加点
    const point = { x: mathX, y: mathY, isInside };
    tutorialSimulation.points.push(point);
    tutorialSimulation.totalPoints++;
    
    if (isInside) {
        tutorialSimulation.insidePoints++;
    }
    
    console.log(`手动添加点: (${mathX.toFixed(3)}, ${mathY.toFixed(3)}), 距离: ${distance.toFixed(3)}, ${isInside ? '圆内' : '圆外'}`);
    
    // 更新显示
    updateTutorialStats();
    drawTutorialCanvas();
}

// 启动实验
function startTutorialSimulation() {
    console.log('startTutorialSimulation called', {
        isRunning: tutorialSimulation.isRunning,
        canvas: !!tutorialSimulation.canvas,
        ctx: !!tutorialSimulation.ctx
    });
    
    if (tutorialSimulation.isRunning) {
        console.log('实验已在运行中，忽略启动请求');
        return;
    }
    
    if (!tutorialSimulation.canvas || !tutorialSimulation.ctx) {
        console.error('画布或上下文不可用，重新初始化');
        initTutorialLab();
        return;
    }
    
    tutorialSimulation.isRunning = true;
    tutorialSimulation.startTime = Date.now();
    tutorialSimulation.lastUpdate = Date.now();
    tutorialSimulation.lastFpsUpdate = Date.now();
    
    // 更新状态显示
    updateExperimentStatus('运行中', ['active', 'active', '']);
    
    // 立即绘制一次画布
    drawTutorialCanvas();
    
    // 开始动画循环
    runTutorialSimulation();
    
    console.log('实验启动成功', {
        startTime: tutorialSimulation.startTime,
        speed: tutorialSimulation.speed,
        batchSize: tutorialSimulation.batchSize
    });
}

// 停止实验
function stopTutorialSimulation() {
    tutorialSimulation.isRunning = false;
    
    if (tutorialSimulation.animationId) {
        cancelAnimationFrame(tutorialSimulation.animationId);
        tutorialSimulation.animationId = null;
    }
    
    // 更新状态显示
    updateExperimentStatus('已停止', ['completed', 'completed', '']);
    
    console.log('实验停止');
}

// 重置实验
function resetTutorialSimulation() {
    stopTutorialSimulation();
    
    tutorialSimulation.totalPoints = 0;
    tutorialSimulation.insidePoints = 0;
    tutorialSimulation.points = [];
    tutorialSimulation.scale = 1;
    tutorialSimulation.offsetX = 0;
    tutorialSimulation.offsetY = 0;
    
    // 更新状态显示
    updateExperimentStatus('等待中', ['active', '', '']);
    
    // 重绘画布
    drawTutorialCanvas();
    updateTutorialStats();
    
    console.log('实验重置');
}

// 更新实验状态
function updateExperimentStatus(status, dotStates) {
    const statusElement = document.getElementById('experimentStatus');
    if (statusElement) statusElement.textContent = status;
    
    const dots = document.querySelectorAll('.experiment-status .dot');
    dotStates.forEach((state, index) => {
        if (dots[index]) {
            dots[index].className = `dot ${state}`;
        }
    });
}

// 保存实验数据
function saveExperimentData() {
    const data = {
        timestamp: new Date().toISOString(),
        totalPoints: tutorialSimulation.totalPoints,
        insidePoints: tutorialSimulation.insidePoints,
        piEstimate: tutorialSimulation.totalPoints > 0 ? 
            4 * (tutorialSimulation.insidePoints / tutorialSimulation.totalPoints) : 0,
        accuracy: tutorialSimulation.totalPoints > 0 ? 
            Math.max(0, 100 - Math.abs((4 * tutorialSimulation.insidePoints / tutorialSimulation.totalPoints) - Math.PI) / Math.PI * 100) : 0,
        runTime: Date.now() - tutorialSimulation.startTime,
        settings: {
            speed: tutorialSimulation.speed,
            batchSize: tutorialSimulation.batchSize,
            particleSize: tutorialSimulation.particleSize,
            displayMode: tutorialSimulation.displayMode
        }
    };
    
    // 保存到历史记录
    tutorialSimulation.history.push(data);
    
    // 更新历史显示
    updateExperimentHistory();
    
    // 下载数据文件
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `monte-carlo-experiment-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    
    console.log('实验数据已保存', data);
}

// 更新实验历史记录
function updateExperimentHistory() {
    const historyList = document.getElementById('experimentHistory');
    if (!historyList || tutorialSimulation.history.length === 0) return;
    
    const recentExperiments = tutorialSimulation.history.slice(-5); // 显示最近5次
    
    historyList.innerHTML = recentExperiments.map(exp => `
        <div class="history-item">
            <div class="history-time">${new Date(exp.timestamp).toLocaleTimeString()}</div>
            <div class="history-data">π=${exp.piEstimate.toFixed(4)} (${exp.accuracy.toFixed(1)}%)</div>
        </div>
    `).join('');
}

// 初始化控制事件
function initTutorialControls() {
    // 启动按钮
    const startBtn = document.getElementById('startAdvancedDemo');
    console.log('启动按钮元素:', startBtn);
    if (startBtn) {
        startBtn.addEventListener('click', (e) => {
            console.log('启动按钮被点击');
            startTutorialSimulation();
        });
        console.log('启动按钮事件监听器已添加');
    } else {
        console.error('找不到启动按钮元素 #startAdvancedDemo');
    }
    
    // 重置按钮
    const resetBtn = document.getElementById('resetAdvancedDemo');
    console.log('重置按钮元素:', resetBtn);
    if (resetBtn) {
        resetBtn.addEventListener('click', (e) => {
            console.log('重置按钮被点击');
            resetTutorialSimulation();
        });
    } else {
        console.error('找不到重置按钮元素 #resetAdvancedDemo');
    }
    
    // 保存按钮
    const saveBtn = document.getElementById('saveExperiment');
    console.log('保存按钮元素:', saveBtn);
    if (saveBtn) {
        saveBtn.addEventListener('click', (e) => {
            console.log('保存按钮被点击');
            saveExperimentData();
        });
    } else {
        console.error('找不到保存按钮元素 #saveExperiment');
    }
    
    // 画布工具按钮
    const zoomInBtn = document.getElementById('zoomIn');
    if (zoomInBtn) {
        zoomInBtn.addEventListener('click', () => {
            tutorialSimulation.scale = Math.min(5, tutorialSimulation.scale * 1.2);
            drawTutorialCanvas();
        });
    }
    
    const zoomOutBtn = document.getElementById('zoomOut');
    if (zoomOutBtn) {
        zoomOutBtn.addEventListener('click', () => {
            tutorialSimulation.scale = Math.max(0.1, tutorialSimulation.scale / 1.2);
            drawTutorialCanvas();
        });
    }
    
    const resetZoomBtn = document.getElementById('resetZoom');
    if (resetZoomBtn) {
        resetZoomBtn.addEventListener('click', () => {
            tutorialSimulation.scale = 1;
            tutorialSimulation.offsetX = 0;
            tutorialSimulation.offsetY = 0;
            drawTutorialCanvas();
        });
    }
    
    // 参数控制
    const speedSlider = document.getElementById('tutorialSpeed');
    if (speedSlider) {
        speedSlider.addEventListener('input', (e) => {
            tutorialSimulation.speed = parseInt(e.target.value);
            const display = document.getElementById('tutorialSpeedDisplay');
            if (display) {
                const speedText = tutorialSimulation.speed < 20 ? '慢' : 
                                  tutorialSimulation.speed < 60 ? '中等' : '快';
                display.textContent = speedText;
            }
        });
    }
    
    const batchSizeSelect = document.getElementById('tutorialBatchSize');
    if (batchSizeSelect) {
        batchSizeSelect.addEventListener('change', (e) => {
            tutorialSimulation.batchSize = parseInt(e.target.value);
        });
    }
    
    const particleSizeSlider = document.getElementById('particleSize');
    if (particleSizeSlider) {
        particleSizeSlider.addEventListener('input', (e) => {
            tutorialSimulation.particleSize = parseFloat(e.target.value);
            const display = document.getElementById('particleSizeDisplay');
            if (display) display.textContent = tutorialSimulation.particleSize + 'px';
            drawTutorialCanvas();
        });
    }
    
    // 显示模式按钮
    const modeBtns = document.querySelectorAll('.mode-btn');
    console.log('找到显示模式按钮:', modeBtns.length);
    modeBtns.forEach((btn, index) => {
        console.log(`按钮 ${index}:`, btn.textContent, btn.dataset.mode);
        btn.addEventListener('click', (e) => {
            console.log('显示模式按钮被点击:', btn.textContent, btn.dataset.mode);
            modeBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            tutorialSimulation.displayMode = btn.dataset.mode;
            drawTutorialCanvas();
        });
    });
}

// 初始化3D控制事件
function init3DControls() {
    // 启动按钮
    const startBtn = document.getElementById('start3DSimulation');
    if (startBtn) {
        startBtn.addEventListener('click', () => {
            if (!isRunning3D) {
                isRunning3D = true;
                updateControlButtons3D();
                generate3DPoints();
            }
        });
    }
    
    // 暂停按钮
    const pauseBtn = document.getElementById('pause3DSimulation');
    if (pauseBtn) {
        pauseBtn.addEventListener('click', () => {
            isRunning3D = false;
            updateControlButtons3D();
        });
    }
    
    // 重置按钮
    const resetBtn = document.getElementById('reset3DSimulation');
    if (resetBtn) {
        resetBtn.addEventListener('click', reset3DSimulation);
    }
    
    // 截图按钮
    const screenshotBtn = document.getElementById('screenshot3D');
    if (screenshotBtn) {
        screenshotBtn.addEventListener('click', () => {
            const link = document.createElement('a');
            link.download = 'monte-carlo-3d-simulation.png';
            link.href = renderer3D.domElement.toDataURL();
            link.click();
        });
    }
    
    // 参数控制
    const particleCountSlider = document.getElementById('particleCount3D');
    if (particleCountSlider) {
        particleCountSlider.addEventListener('input', (e) => {
            particleCount3D = parseInt(e.target.value);
            const valueDisplay = document.getElementById('particleCount3DValue');
            if (valueDisplay) valueDisplay.textContent = particleCount3D.toLocaleString();
        });
    }
    
    const speedSlider = document.getElementById('animationSpeed3D');
    if (speedSlider) {
        speedSlider.addEventListener('input', (e) => {
            animationSpeed3D = parseFloat(e.target.value);
            const valueDisplay = document.getElementById('animationSpeed3DValue');
            if (valueDisplay) valueDisplay.textContent = animationSpeed3D.toFixed(1) + 'x';
        });
    }
    
    const pointSizeSlider = document.getElementById('pointSize3D');
    if (pointSizeSlider) {
        pointSizeSlider.addEventListener('input', (e) => {
            pointSize3D = parseFloat(e.target.value);
            const valueDisplay = document.getElementById('pointSize3DValue');
            if (valueDisplay) valueDisplay.textContent = pointSize3D.toFixed(1);
        });
    }
    
    // 显示选项切换
    const gridToggle = document.getElementById('showGrid3D');
    if (gridToggle) {
        gridToggle.addEventListener('change', (e) => {
            showGrid3D = e.target.checked;
            const grid = scene3D.getObjectByName('grid');
            if (grid) grid.visible = showGrid3D;
        });
    }
    
    const axesToggle = document.getElementById('showAxes3D');
    if (axesToggle) {
        axesToggle.addEventListener('change', (e) => {
            showAxes3D = e.target.checked;
            const axes = scene3D.getObjectByName('axes');
            if (axes) axes.visible = showAxes3D;
        });
    }
    
    const rotationToggle = document.getElementById('enableRotation3D');
    if (rotationToggle) {
        rotationToggle.addEventListener('change', (e) => {
            enableRotation3D = e.target.checked;
        });
    }
    
    // 视角预设
    const viewPresets = document.querySelectorAll('.view-preset');
    viewPresets.forEach(preset => {
        preset.addEventListener('click', () => {
            const presetType = preset.dataset.preset;
            
            // 移除其他活动状态
            viewPresets.forEach(p => p.classList.remove('active'));
            preset.classList.add('active');
            
            // 设置相机位置
            switch (presetType) {
                case 'default':
                    camera3D.position.set(4, 4, 4);
                    break;
                case 'top':
                    camera3D.position.set(0, 6, 0);
                    break;
                case 'side':
                    camera3D.position.set(6, 0, 0);
                    break;
                case 'perspective':
                    camera3D.position.set(4, 3, 5);
                    break;
            }
            camera3D.lookAt(0, 0, 0);
        });
    });
    
    // 信息面板切换
    const infoToggle = document.getElementById('infoToggle3D');
    const infoContent = document.getElementById('infoContent3D');
    if (infoToggle && infoContent) {
        infoToggle.addEventListener('click', () => {
            infoContent.classList.toggle('show');
        });
    }
}

// 当页面加载完成时初始化
window.addEventListener('DOMContentLoaded', () => {
    // 先启动加载屏幕
    initLoader();
    
    setupErrorHandling();
    setupPerformanceMonitoring();
    checkCompatibility();
    enableDebugMode();
    init();
    
    // 初始化性能监控面板
    setTimeout(() => {
        initPerformanceMonitor();
    }, 1500);

    // 运行基础测试
    setTimeout(() => {
        runBasicTests();
    }, 1000);
    
    // 初始化互动实验室（延迟更长时间确保DOM完全加载）
    setTimeout(() => {
        console.log('开始初始化互动实验室...');
        console.log('当前页面状态:', document.readyState);
        console.log('DOM元素检查:');
        console.log('- tutorialCanvas:', !!document.getElementById('tutorialCanvas'));
        console.log('- startAdvancedDemo:', !!document.getElementById('startAdvancedDemo'));
        console.log('- mode-btn数量:', document.querySelectorAll('.mode-btn').length);
        
        initTutorialLab();
        
        // 在控制台中暴露测试函数，方便手动调用
        window.testTutorialLab = testTutorialLab;
        window.tutorialSimulation = tutorialSimulation;
        console.log('可用的调试函数:');
        console.log('- testTutorialLab(): 运行完整的功能测试');
        console.log('- tutorialSimulation: 查看模拟器状态');
    }, 3000);
    
    // 初始化3D功能（延迟加载以确保Three.js库已加载）
    setTimeout(() => {
        if (typeof THREE !== 'undefined') {
            init3D();
            init3DControls();
            console.log('3D功能初始化完成');
        } else {
            console.warn('Three.js library not loaded. 3D functionality disabled.');
        }
    }, 2500);
    
    // 初始化算法对比功能
    setTimeout(() => {
        initAlgorithmComparison();
        console.log('算法对比功能初始化完成');
    }, 1000);
});

// 算法对比功能实现
let isComparisonRunning = false;
let comparisonData = {
    'monte-carlo': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], inside: 0, total: 0 },
    'leibniz': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], sum: 0 },
    'nilakantha': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], currentPi: 3 },
    'buffon': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], crossings: 0, total: 0 }
};

// 图表实例
let convergenceChart = null;
let radarChart = null;

// 初始化算法对比
function initAlgorithmComparison() {
    console.log('初始化算法对比功能...');
    
    // 初始化算法卡片选择
    initAlgorithmCards();
    
    // 初始化控制按钮
    initComparisonControls();
    
    // 初始化图表
    initComparisonCharts();
    
    // 添加调试函数
    window.testAlgorithmComparison = function() {
        console.log('=== 算法对比测试 ===');
        console.log('开始测试算法对比功能...');
        
        // 模拟选中所有算法
        document.querySelectorAll('.algorithm-card-enhanced').forEach(card => {
            card.classList.add('selected');
        });
        
        // 设置轻量级测试
        document.querySelectorAll('.intensity-btn').forEach(btn => btn.classList.remove('active'));
        const lightBtn = document.querySelector('.intensity-btn[data-iterations="1000"]');
        if (lightBtn) {
            lightBtn.classList.add('active');
        }
        
        console.log('已选中所有算法，设置轻量级测试(1000次迭代)');
        
        // 开始对比
        startBattleComparison();
    };
    
window.debugComparisonData = function() {
    console.log('=== 当前对比数据 ===');
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        console.log(`${algorithm}:`, {
            π值: data.pi.toFixed(6),
            精度: data.accuracy.toFixed(2) + '%',
            迭代: data.iterations,
            进度: data.progress.toFixed(1) + '%',
            历史数据点: data.history ? data.history.length : 0
        });
        if (data.history && data.history.length > 0) {
            console.log(`  最近的历史点:`, data.history.slice(-3));
        }
    });
};

// 调试：手动刷新图表
window.refreshCharts = function() {
    console.log('=== 手动刷新图表 ===');
    initComparisonCharts();
    updateCharts();
    console.log('图表刷新完成');
};
    
    console.log('算法对比功能初始化完成');
    console.log('可用调试函数:');
    console.log('- testAlgorithmComparison(): 自动测试所有算法');
    console.log('- debugComparisonData(): 查看当前对比数据');
    console.log('- refreshCharts(): 手动刷新图表');
}

// 初始化算法卡片选择
function initAlgorithmCards() {
    const cards = document.querySelectorAll('.algorithm-card-enhanced');
    console.log('找到算法卡片:', cards.length);
    
    cards.forEach(card => {
        card.addEventListener('click', () => {
            card.classList.toggle('selected');
            console.log('卡片选择状态改变:', card.dataset.algorithm, card.classList.contains('selected'));
        });
    });
    
    // 默认选中蒙特卡洛
    const monteCarloCard = document.querySelector('[data-algorithm="monte-carlo"]');
    if (monteCarloCard) {
        monteCarloCard.classList.add('selected');
    }
}

// 初始化对比控制
function initComparisonControls() {
    // 选择控制按钮
    const selectAllBtn = document.getElementById('selectAllAlgorithms');
    const clearAllBtn = document.getElementById('clearAllAlgorithms');
    const resetBtn = document.getElementById('resetAlgorithms');
    
    if (selectAllBtn) {
        selectAllBtn.addEventListener('click', () => {
            document.querySelectorAll('.algorithm-card-enhanced').forEach(card => {
                card.classList.add('selected');
            });
        });
    }
    
    if (clearAllBtn) {
        clearAllBtn.addEventListener('click', () => {
            document.querySelectorAll('.algorithm-card-enhanced').forEach(card => {
                card.classList.remove('selected');
            });
        });
    }
    
    if (resetBtn) {
        resetBtn.addEventListener('click', () => {
            resetComparison();
        });
    }
    
    // 竞技控制按钮
    const startBattleBtn = document.getElementById('startBattleComparison');
    const pauseBattleBtn = document.getElementById('pauseBattleComparison');
    
    if (startBattleBtn) {
        startBattleBtn.addEventListener('click', startBattleComparison);
    }
    
    if (pauseBattleBtn) {
        pauseBattleBtn.addEventListener('click', pauseBattleComparison);
    }
    
    // 强度选择器
    const intensityBtns = document.querySelectorAll('.intensity-btn');
    intensityBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            intensityBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
        });
    });
}

// 开始竞技对比
function startBattleComparison() {
    if (isComparisonRunning) {
        console.log('对比已在运行中');
        return;
    }
    
    const selectedCards = document.querySelectorAll('.algorithm-card-enhanced.selected');
    if (selectedCards.length === 0) {
        alert('请至少选择一个算法进行对比！');
        return;
    }
    
    const activeIntensity = document.querySelector('.intensity-btn.active');
    const iterations = parseInt(activeIntensity?.dataset.iterations || '10000');
    
    console.log('开始算法对比:', selectedCards.length, '个算法,', iterations, '次迭代');
    
    isComparisonRunning = true;
    
    // 更新UI状态
    updateCompetitorStatus('running');
    
    // 重置数据
    resetComparisonData();
    
    // 运行选中的算法
    selectedCards.forEach(card => {
        const algorithm = card.dataset.algorithm;
        runAlgorithmComparison(algorithm, iterations);
    });
}

// 暂停对比
function pauseBattleComparison() {
    isComparisonRunning = false;
    updateCompetitorStatus('ready');
    console.log('算法对比已暂停');
}

// 重置对比数据
function resetComparisonData() {
    comparisonData = {
        'monte-carlo': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], inside: 0, total: 0 },
        'leibniz': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], sum: 0 },
        'nilakantha': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], currentPi: 3 },
        'buffon': { pi: 0, accuracy: 0, time: 0, iterations: 0, progress: 0, history: [], crossings: 0, total: 0 }
    };
    updateComparisonDisplay();
    updateCharts();
}

// 重置对比
function resetComparison() {
    isComparisonRunning = false;
    resetComparisonData();
    updateCompetitorStatus('ready');
    
    // 重置进度条
    document.querySelectorAll('.progress-bar').forEach(bar => {
        bar.style.width = '0%';
    });
    
    console.log('对比已重置');
}

// 运行算法对比
async function runAlgorithmComparison(algorithm, iterations) {
    const startTime = Date.now();
    let currentIteration = 0;
    const batchSize = 100; // 减小批次大小，让更新更频繁
    
    while (currentIteration < iterations && isComparisonRunning) {
        const batch = Math.min(batchSize, iterations - currentIteration);
        
        // 运行算法
        const result = runAlgorithmBatch(algorithm, batch, currentIteration);
        
        currentIteration += batch;
        const progress = (currentIteration / iterations) * 100;
        const elapsedTime = Date.now() - startTime;
        
        // 更新数据 - 保持累积数据结构
        const currentData = comparisonData[algorithm];
        comparisonData[algorithm] = {
            ...currentData,  // 保持累积数据 (inside, total, sum, currentPi, crossings)
            pi: result.pi,
            accuracy: calculateAccuracy(result.pi),
            time: elapsedTime,
            iterations: currentIteration,
            progress: progress
        };
        
        // 添加历史记录（每100次迭代记录一次，更频繁的数据点）
        if (currentIteration % 100 === 0) {
            if (!comparisonData[algorithm].history) {
                comparisonData[algorithm].history = [];
            }
            comparisonData[algorithm].history.push({
                iterations: currentIteration,
                pi: result.pi,
                accuracy: comparisonData[algorithm].accuracy,
                time: elapsedTime
            });
            console.log(`记录历史数据 ${algorithm}: 迭代=${currentIteration}, π=${result.pi.toFixed(6)}`);
        }
        
        // 更新显示
        updateComparisonDisplay();
        
        // 更新图表
        updateCharts();
        
        // 更新进度条
        updateProgressBar(algorithm, progress);
        
        // 给UI一些喘息时间
        await new Promise(resolve => setTimeout(resolve, 10));
    }
    
    // 算法完成
    if (currentIteration >= iterations) {
        console.log(`${algorithm} 算法完成:`, comparisonData[algorithm]);
        updateCompetitorStatus('finished', algorithm);
    }
}

// 运行算法批次
function runAlgorithmBatch(algorithm, batchSize, currentIteration) {
    switch (algorithm) {
        case 'monte-carlo':
            return runMonteCarloBatch(algorithm, batchSize);
        case 'leibniz':
            return runLeibnizBatch(algorithm, batchSize, currentIteration);
        case 'nilakantha':
            return runNilakanthaBatch(algorithm, batchSize, currentIteration);
        case 'buffon':
            return runBuffonBatch(algorithm, batchSize);
        default:
            return { pi: 0 };
    }
}

// 蒙特卡洛批次计算 - 累积版本
function runMonteCarloBatch(algorithm, batchSize) {
    const data = comparisonData[algorithm];
    
    // 累积计算新的批次
    for (let i = 0; i < batchSize; i++) {
        const x = Math.random() * 2 - 1;
        const y = Math.random() * 2 - 1;
        if (x * x + y * y <= 1) {
            data.inside++;
        }
        data.total++;
    }
    
    // 计算当前π值估算
    const pi = data.total > 0 ? (data.inside / data.total) * 4 : 0;
    
    console.log(`蒙特卡洛: ${data.inside}/${data.total}, π=${pi.toFixed(6)}`);
    
    return { pi: pi };
}

// 莱布尼兹级数批次计算 - 累积版本
function runLeibnizBatch(algorithm, batchSize, currentIteration) {
    const data = comparisonData[algorithm];
    
    // 确保sum已初始化
    if (typeof data.sum !== 'number') {
        data.sum = 0;
    }
    
    // 从当前项开始计算新的批次
    for (let i = 0; i < batchSize; i++) {
        const term_index = currentIteration + i;
        const term = Math.pow(-1, term_index) / (2 * term_index + 1);
        if (!isNaN(term) && isFinite(term)) {
            data.sum += term;
        }
    }
    
    // π = 4 * sum
    const pi = isFinite(data.sum) ? data.sum * 4 : 0;
    
    console.log(`莱布尼兹: 项数=${currentIteration + batchSize}, sum=${data.sum.toFixed(8)}, π=${pi.toFixed(6)}`);
    
    return { pi: pi };
}

// 尼拉卡塔级数批次计算 - 累积版本  
function runNilakanthaBatch(algorithm, batchSize, currentIteration) {
    const data = comparisonData[algorithm];
    
    // 确保currentPi已初始化
    if (typeof data.currentPi !== 'number' || !isFinite(data.currentPi)) {
        data.currentPi = 3;
    }
    
    // 计算要添加的项数 (每50次迭代添加一项)
    const termsToAdd = Math.floor(batchSize / 50);
    const startTerm = Math.floor(currentIteration / 50) + 1;
    
    // 添加新的项
    for (let j = 0; j < termsToAdd; j++) {
        const term_index = startTerm + j;
        const denominator = (2 * term_index) * (2 * term_index + 1) * (2 * term_index + 2);
        if (denominator !== 0) {
            const term = 4 / denominator;
            if (!isNaN(term) && isFinite(term)) {
                data.currentPi += term_index % 2 === 1 ? term : -term;
            }
        }
    }
    
    const pi = isFinite(data.currentPi) ? data.currentPi : 3;
    
    console.log(`尼拉卡塔: 项数=${Math.floor((currentIteration + batchSize) / 50)}, π=${pi.toFixed(6)}`);
    
    return { pi: pi };
}

// 布丰投针批次计算 - 累积版本
function runBuffonBatch(algorithm, batchSize) {
    const data = comparisonData[algorithm];
    const L = 1; // 针长
    const d = 2; // 线间距
    
    // 累积计算新的批次
    for (let i = 0; i < batchSize; i++) {
        const y = Math.random() * d / 2;
        const angle = Math.random() * Math.PI;
        if (y <= (L / 2) * Math.sin(angle)) {
            data.crossings++;
        }
        data.total++;
    }
    
    // 计算当前π值估算
    const pi = data.crossings > 0 ? (2 * L * data.total) / (data.crossings * d) : 0;
    
    console.log(`布丰投针: ${data.crossings}/${data.total}, π=${pi.toFixed(6)}`);
    
    return { pi: pi };
}

// 计算精度
function calculateAccuracy(pi) {
    const realPi = Math.PI;
    const accuracy = Math.max(0, 100 - Math.abs((pi - realPi) / realPi) * 100);
    return Math.round(accuracy * 100) / 100;
}

// 更新对比显示
function updateComparisonDisplay() {
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        
        // 更新π值
        const piElement = document.getElementById(getResultElementId(algorithm, 'pi'));
        if (piElement) {
            piElement.textContent = data.pi.toFixed(6);
        } else {
            console.warn(`π值元素未找到: ${getResultElementId(algorithm, 'pi')}`);
        }
        
        // 更新精度
        const accuracyElement = document.getElementById(getResultElementId(algorithm, 'accuracy'));
        if (accuracyElement) {
            accuracyElement.textContent = data.accuracy.toFixed(2) + '%';
        } else {
            console.warn(`精度元素未找到: ${getResultElementId(algorithm, 'accuracy')}`);
        }
        
        // 更新时间
        const timeElement = document.getElementById(getResultElementId(algorithm, 'time'));
        if (timeElement) {
            timeElement.textContent = (data.time / 1000).toFixed(2) + 's';
        } else {
            console.warn(`时间元素未找到: ${getResultElementId(algorithm, 'time')}`);
        }
        
        console.log(`更新显示 ${algorithm}:`, {
            pi: data.pi.toFixed(6),
            accuracy: data.accuracy.toFixed(2) + '%', 
            time: (data.time / 1000).toFixed(2) + 's'
        });
    });
}

// 获取结果元素ID
function getResultElementId(algorithm, type) {
    const mapping = {
        'monte-carlo': { pi: 'mcResultEnhanced', accuracy: 'mcAccuracyEnhanced', time: 'mcTimeEnhanced' },
        'leibniz': { pi: 'leibnizResultEnhanced', accuracy: 'leibnizAccuracyEnhanced', time: 'leibnizTimeEnhanced' },
        'nilakantha': { pi: 'nilakanthaResultEnhanced', accuracy: 'nilakanthaAccuracyEnhanced', time: 'nilakanthaTimeEnhanced' },
        'buffon': { pi: 'buffonResultEnhanced', accuracy: 'buffonAccuracyEnhanced', time: 'buffonTimeEnhanced' }
    };
    
    return mapping[algorithm]?.[type] || null;
}

// 更新进度条
function updateProgressBar(algorithm, progress) {
    const progressIdMap = {
        'monte-carlo': 'mcProgress',
        'leibniz': 'leibnizProgress', 
        'nilakantha': 'nilakanthaProgress',
        'buffon': 'buffonProgress'
    };
    
    const progressElement = document.getElementById(progressIdMap[algorithm]);
    if (progressElement) {
        progressElement.style.width = progress + '%';
        console.log(`更新进度条 ${algorithm}: ${progress}%`);
    } else {
        console.warn(`进度条元素未找到: ${progressIdMap[algorithm]}`);
    }
}

// 更新竞争者状态
function updateCompetitorStatus(status, algorithm = null) {
    const statusMap = {
        'ready': '就绪',
        'running': '运行中',
        'finished': '完成'
    };
    
    if (algorithm) {
        const statusElement = document.querySelector(`[data-algorithm="${algorithm}"] .competitor-status`);
        if (statusElement) {
            statusElement.textContent = statusMap[status];
            statusElement.className = `competitor-status ${status}`;
        }
        
        const competitorElement = document.querySelector(`[data-algorithm="${algorithm}"]`);
        if (competitorElement && status === 'running') {
            competitorElement.classList.add('running');
        } else if (competitorElement) {
            competitorElement.classList.remove('running');
        }
    } else {
        // 更新所有状态
        document.querySelectorAll('.competitor-status').forEach(element => {
            element.textContent = statusMap[status];
            element.className = `competitor-status ${status}`;
        });
        
        document.querySelectorAll('.competitor').forEach(element => {
            if (status === 'running') {
                element.classList.add('running');
            } else {
                element.classList.remove('running');
            }
        });
    }
}

// 初始化对比图表
function initComparisonCharts() {
    console.log('初始化对比图表...');
    initConvergenceChart();
    initRadarChart();
}

// 初始化收敛性图表
function initConvergenceChart() {
    const canvas = document.getElementById('convergenceComparisonChart');
    if (!canvas) {
        console.warn('收敛性图表画布未找到');
        return;
    }
    
    const ctx = canvas.getContext('2d');
    if (!ctx) {
        console.warn('无法获取图表上下文');
        return;
    }
    
    // 设置高分辨率画布
    const rect = canvas.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    
    ctx.scale(dpr, dpr);
    
    // 设置画布样式大小
    canvas.style.width = rect.width + 'px';
    canvas.style.height = rect.height + 'px';
    
    console.log('收敛性图表尺寸:', canvas.width, 'x', canvas.height);
    
    // 手动绘制收敛图表
    drawConvergenceChart(ctx, canvas.width / dpr, canvas.height / dpr);
    
    console.log('收敛性图表初始化完成');
}

// 绘制收敛性图表
function drawConvergenceChart(ctx, width, height) {
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 设置样式
    const padding = 60;
    const chartWidth = width - 2 * padding;
    const chartHeight = height - 2 * padding;
    
    // 绘制背景网格
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.lineWidth = 1;
    
    // 垂直网格线
    for (let i = 0; i <= 10; i++) {
        const x = padding + (chartWidth * i) / 10;
        ctx.beginPath();
        ctx.moveTo(x, padding);
        ctx.lineTo(x, height - padding);
        ctx.stroke();
    }
    
    // 水平网格线
    for (let i = 0; i <= 8; i++) {
        const y = padding + (chartHeight * i) / 8;
        ctx.beginPath();
        ctx.moveTo(padding, y);
        ctx.lineTo(width - padding, y);
        ctx.stroke();
    }
    
    // 绘制坐标轴
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.lineWidth = 2;
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(padding, height - padding);
    ctx.lineTo(width - padding, height - padding);
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, height - padding);
    ctx.stroke();
    
    // 绘制轴标签
    ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    
    // X轴标签
    ctx.fillText('迭代次数', width / 2, height - 20);
    
    // Y轴标签
    ctx.save();
    ctx.translate(20, height / 2);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText('π值', 0, 0);
    ctx.restore();
    
    // 绘制π的真实值线
    const piY = height - padding - ((Math.PI - 2.5) / (3.5 - 2.5)) * chartHeight;
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.beginPath();
    ctx.moveTo(padding, piY);
    ctx.lineTo(width - padding, piY);
    ctx.stroke();
    ctx.setLineDash([]);
    
    // π值标签
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    ctx.textAlign = 'left';
    ctx.fillText('π = 3.14159...', padding + 10, piY - 5);
    
    // 绘制算法收敛曲线
    const colors = {
        'monte-carlo': '#6366f1',
        'leibniz': '#ec4899', 
        'nilakantha': '#10b981',
        'buffon': '#f59e0b'
    };
    
    // 找到最大迭代次数用于缩放
    let maxIterations = 1000;
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        if (data.iterations > maxIterations) {
            maxIterations = data.iterations;
        }
    });
    
    console.log('绘制收敛曲线, 最大迭代次数:', maxIterations);
    
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        console.log(`绘制 ${algorithm}: 历史数据点=${data.history ? data.history.length : 0}`);
        
        if (data.history && data.history.length > 0) {
            ctx.strokeStyle = colors[algorithm];
            ctx.lineWidth = 3;
            ctx.beginPath();
            
            let hasDrawnFirst = false;
            
            data.history.forEach((point, index) => {
                if (point && typeof point.pi === 'number' && isFinite(point.pi)) {
                    const x = padding + (point.iterations / maxIterations) * chartWidth;
                    const y = height - padding - ((Math.max(2.5, Math.min(3.5, point.pi)) - 2.5) / 1) * chartHeight;
                    
                    if (!hasDrawnFirst) {
                        ctx.moveTo(x, y);
                        hasDrawnFirst = true;
                    } else {
                        ctx.lineTo(x, y);
                    }
                    
                    console.log(`  点${index}: (${point.iterations}, ${point.pi.toFixed(3)}) -> 画布(${x.toFixed(1)}, ${y.toFixed(1)})`);
                }
            });
            
            ctx.stroke();
            
            // 绘制算法名称标签
            if (data.history.length > 0) {
                const lastPoint = data.history[data.history.length - 1];
                if (lastPoint && typeof lastPoint.pi === 'number') {
                    const x = padding + (lastPoint.iterations / maxIterations) * chartWidth;
                    const y = height - padding - ((Math.max(2.5, Math.min(3.5, lastPoint.pi)) - 2.5) / 1) * chartHeight;
                    
                    ctx.fillStyle = colors[algorithm];
                    ctx.font = '12px Arial';
                    ctx.fillText(algorithm, x + 10, y - 10);
                }
            }
        }
    });
    
    // 绘制当前值点
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        if (data.iterations > 0 && typeof data.pi === 'number' && isFinite(data.pi)) {
            const x = padding + (data.iterations / maxIterations) * chartWidth;
            const y = height - padding - ((Math.max(2.5, Math.min(3.5, data.pi)) - 2.5) / 1) * chartHeight;
            
            // 绘制外圈
            ctx.fillStyle = colors[algorithm];
            ctx.beginPath();
            ctx.arc(x, y, 6, 0, 2 * Math.PI);
            ctx.fill();
            
            // 绘制内圈
            ctx.fillStyle = 'white';
            ctx.beginPath();
            ctx.arc(x, y, 3, 0, 2 * Math.PI);
            ctx.fill();
            
            console.log(`当前值点 ${algorithm}: π=${data.pi.toFixed(6)} 位置=(${x.toFixed(1)}, ${y.toFixed(1)})`);
        }
    });
}

// 初始化雷达图
function initRadarChart() {
    const canvas = document.getElementById('performanceRadarChart');
    if (!canvas) {
        console.warn('雷达图画布未找到');
        return;
    }
    
    const ctx = canvas.getContext('2d');
    if (!ctx) {
        console.warn('无法获取雷达图上下文');
        return;
    }
    
    // 设置高分辨率画布
    const rect = canvas.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    
    ctx.scale(dpr, dpr);
    
    // 设置画布样式大小
    canvas.style.width = rect.width + 'px';
    canvas.style.height = rect.height + 'px';
    
    console.log('雷达图尺寸:', canvas.width, 'x', canvas.height);
    
    // 手动绘制雷达图
    drawRadarChart(ctx, canvas.width / dpr, canvas.height / dpr);
    
    console.log('雷达图初始化完成');
}

// 绘制雷达图
function drawRadarChart(ctx, width, height) {
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 检查画布尺寸
    if (width < 100 || height < 100) {
        console.warn('雷达图画布尺寸太小，跳过绘制');
        return;
    }
    
    const centerX = width / 2;
    const centerY = height / 2;
    const radius = Math.max(30, Math.min(width, height) / 2 - 60); // 确保radius至少为30
    
    console.log(`雷达图绘制参数: 尺寸=${width}x${height}, 半径=${radius}`);
    
    // 性能维度
    const dimensions = [
        { name: '精度', key: 'accuracy' },
        { name: '速度', key: 'speed' },
        { name: '收敛性', key: 'convergence' },
        { name: '稳定性', key: 'stability' }
    ];
    
    // 绘制雷达网格
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
    ctx.lineWidth = 1;
    
    // 绘制同心圆
    for (let i = 1; i <= 5; i++) {
        const r = Math.max(1, (radius * i) / 5); // 确保半径至少为1
        ctx.beginPath();
        ctx.arc(centerX, centerY, r, 0, 2 * Math.PI);
        ctx.stroke();
    }
    
    // 绘制轴线和标签
    dimensions.forEach((dim, index) => {
        const angle = (index * 2 * Math.PI) / dimensions.length - Math.PI / 2;
        const x1 = centerX + Math.cos(angle) * radius;
        const y1 = centerY + Math.sin(angle) * radius;
        
        // 绘制轴线
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.lineTo(x1, y1);
        ctx.stroke();
        
        // 绘制标签
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        const labelX = centerX + Math.cos(angle) * (radius + 30);
        const labelY = centerY + Math.sin(angle) * (radius + 30);
        ctx.fillText(dim.name, labelX, labelY);
    });
    
    // 绘制算法性能数据
    const colors = {
        'monte-carlo': '#6366f1',
        'leibniz': '#ec4899',
        'nilakantha': '#10b981',
        'buffon': '#f59e0b'
    };
    
    Object.keys(comparisonData).forEach(algorithm => {
        const data = comparisonData[algorithm];
        if (data.iterations > 0) {
            // 计算性能指标（0-100）
            const performance = {
                accuracy: Math.max(0, Math.min(data.accuracy || 0, 100)),
                speed: Math.max(0, Math.min(100 - Math.min(data.time / 100, 100), 100)), // 时间越少分数越高
                convergence: Math.max(0, Math.min(getConvergenceScore(algorithm), 100)),
                stability: Math.max(0, Math.min(getStabilityScore(algorithm, data), 100))
            };
            
            // 绘制多边形
            ctx.strokeStyle = colors[algorithm];
            ctx.fillStyle = colors[algorithm] + '20';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            dimensions.forEach((dim, index) => {
                const angle = (index * 2 * Math.PI) / dimensions.length - Math.PI / 2;
                const value = Math.max(0, performance[dim.key] || 0);
                const r = Math.max(0, (radius * value) / 100);
                const x = centerX + Math.cos(angle) * r;
                const y = centerY + Math.sin(angle) * r;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
            
            // 绘制数据点
            dimensions.forEach((dim, index) => {
                const angle = (index * 2 * Math.PI) / dimensions.length - Math.PI / 2;
                const value = Math.max(0, performance[dim.key] || 0);
                const r = Math.max(0, (radius * value) / 100);
                const x = centerX + Math.cos(angle) * r;
                const y = centerY + Math.sin(angle) * r;
                
                ctx.fillStyle = colors[algorithm];
                ctx.beginPath();
                ctx.arc(x, y, Math.max(1, 3), 0, 2 * Math.PI); // 确保点的半径至少为1
                ctx.fill();
            });
        }
    });
}

// 获取收敛分数
function getConvergenceScore(algorithm) {
    const scores = {
        'monte-carlo': 60,  // 中等收敛
        'leibniz': 20,      // 慢收敛
        'nilakantha': 90,   // 快收敛
        'buffon': 55        // 中等收敛
    };
    return scores[algorithm] || 50;
}

// 获取稳定性分数
function getStabilityScore(algorithm, data) {
    if (!data.history || data.history.length < 2) return 50;
    
    // 计算π值的标准差
    const piValues = data.history.map(h => h.pi).filter(pi => typeof pi === 'number' && isFinite(pi));
    if (piValues.length < 2) return 50;
    
    const mean = piValues.reduce((a, b) => a + b) / piValues.length;
    const variance = piValues.reduce((a, b) => a + (b - mean) ** 2, 0) / piValues.length;
    const stdDev = Math.sqrt(variance);
    
    // 标准差越小，稳定性越高
    const score = 100 - stdDev * 50;
    return Math.max(0, Math.min(100, isFinite(score) ? score : 50));
}

// 更新图表
function updateCharts() {
    const convergenceCanvas = document.getElementById('convergenceComparisonChart');
    if (convergenceCanvas) {
        const ctx = convergenceCanvas.getContext('2d');
        if (ctx) {
            const dpr = window.devicePixelRatio || 1;
            drawConvergenceChart(ctx, convergenceCanvas.width / dpr, convergenceCanvas.height / dpr);
        }
    }
    
    const radarCanvas = document.getElementById('performanceRadarChart');
    if (radarCanvas) {
        const ctx = radarCanvas.getContext('2d');
        if (ctx) {
            const dpr = window.devicePixelRatio || 1;
            drawRadarChart(ctx, radarCanvas.width / dpr, radarCanvas.height / dpr);
        }
    }
}
